MySQL, display data not shown when using '=' command - mysql

Is there a way for me to also print out values not equal to each other?
I used a command:
WHERE displayname = personnel
I have 800+ data not shown, how can I show these data?
Note personnel and data are from two different tables.
My whole script looks like this:
SELECT a.something, a.somethins2, b.something1, b.something2
FROM a, b
WHERE a.displayname = b.personnel

!= is the "not equals" operator, so you could have a WHERE displayname != personnel clause. A full query would probably look like this:
SELECT displayname, personnel
FROM some_table t1
JOIN some_other_table t2 ON t1.id = t2.id
WHERE displayname != personnel

Try with this
select * from table_name1 t1,table_name2 t2 where
column_name!='".$data."'
and t2.id=t1.id

if you are trying to get the record that matched a.displayname = b.personnel and not matched from table a:
SELECT a.something, a.somethins2, b.something1, b.something2
FROM a LEFT JOIN b
ON a.displayname = b.personnel

Related

Cross Referencing Multiple Tables

What I was trying to do is to get data from multiple tables, supposed that I have the following results in my query:
The numbers in the column ticket_item_type represents certain table. For example, 2 is for tbl_company and 3 is for tbl_lease. Then the details represents the id of a certain record in that table.
Suppose that I want to get the title of those records using ticket_item_type and details. Is it possible to embed it to the results? Or should I make separate queries for each.
I know JOIN, but I is it only for single table?
Here's my MYSQL query for the image above:
SELECT *
FROM
(SELECT *
FROM ticket_items
WHERE hs_customer = 1
AND ticket IN
(SELECT id
FROM tickets
WHERE hs_customer='1'
AND ticket_status = 'dispatch_reviewed')
AND ticket IN
(SELECT ticket
FROM ticket_items
WHERE ticket_item_type = 5
AND details = '159')) AS TB1
WHERE ticket_item_type IN (3,
2,
8)
You could try something like this:
SELECT
TB1.*,
CASE
WHEN TB1.ticket_item_type = 2 THEN t2.title
WHEN TB1.ticket_item_type = 3 THEN t3.title
WHEN TB1.ticket_item_type = 8 THEN t8.title
ELSE 'NA'
END as title
FROM
(
SELECT *
FROM ticket_items
WHERE hs_customer = 1
AND ticket IN (SELECT id FROM tickets WHERE hs_customer='1' AND ticket_status = 'dispatch_reviewed')
AND ticket IN (SELECT ticket FROM ticket_items WHERE ticket_item_type = 5 AND details = '159')
) AS TB1
LEFT JOIN tbl_company t2 ON TB1.details = t2.id
LEFT JOIN tbl_lease t3 ON TB1.details = t3.id
LEFT JOIN tbl_next t8 ON TB1.details = t8.id
WHERE ticket_item_type IN (3, 2, 8)
However, this is not a design that I would prefer. Without looking at details of your database it's going to be hard to write a query to cover multiple types of ticket_item_type. I hope this query works for you, though.

(another) LEFT JOIN issue with ACCESS

I want summary data from my 'Data' table for all companies in 'Companies' table including blank rows where there is no record in Data.
If I summarise the data in a nested SELECT clause (or in a stored query i get nothing from the data table. For example
This is the sub select
SELECT transco,
sum(m1) AS Jan15,
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco
which outputs:
transco Jan15
0292 154373665
1419 134915098
If I use it in a sub select as follows
SELECT c.SAP_Code,
Jan15
FROM Companies AS c
LEFT JOIN (
SELECT transco,
sum(m1) as Jan15
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco)
AS d
ON c.SAP_Code = d.transco
I get:
SAP_Code Jan15
0292
1419
I can get the correct result via a temporary table:
SELECT sum(m1) as Jan15,
transco
INTO Temp_Table
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco
followed by
Select c.SAP_code,
jan15
FROM companies AS c
LEFT JOIN Temp_Table as i
ON (c.SAP_Code = i.transco)
giving:
SAP_code jan15
0292 154373665
1419 134915098
1423
but if I use temporary tables I will have to create macros and i want users to be able to run just a query.
The following works for this simple case but I can't apply it in other circumstances:
SELECT c.SAP_Code,
sum(m1) AS Jan15
FROM Companies AS c
LEFT JOIN data as d
ON c.SAP_Code = d.transco
WHERE (d.QVmeasure = 'Vol') OR (d.QVmeasure is null)
GROUP BY d.QVmeasure,c.sap_code
Is there something wrong with my sub select syntax or is it ACCESS (2013)
TIA
You could nest the sub-query like this:
SELECT c.SAP_Code,
(SELECT sum(d.m1)
FROM data AS d
WHERE d.QVmeasure = 'Vol' AND c.SAP_Code = d.transco
) AS [Jan15]
FROM Companies AS c

SQL update table using select from and multiple joins

Here are the relevant columns of my tables
bia_panels ( id, sign_id, value, project_id )
bia_clients ( id, name )
bia_projects ( id, name, client_id, city_id )
bia_cities ( id, name )
I am attempting to update the bia_panels.project_id to the bia_projects.id where the bia_panels.value = bia_clients.name and the panels.project_id =000 and the value is not blank of course I must use multiple joins to get there
-- UPDATE
SELECT * FROM
`bia_panels` AS t1
JOIN bia_clients AS t2
ON t1.value = t2.name
JOIN bia_projects AS t3
ON t2.id = t3.client_id
-- SET t1.project_id = t3.id
-- WHERE t1.value<>'' AND t1.project_id = '000'
WHERE t1.value <>''
The problem is that this is not giving me the correct results (my project ids are not correct somewhere in the joins multiple results are returned so they break
I know that once I am able to get the select portion correct I can use an update
For example there may be multiple panels where the value=client.name but not all of them are the same project ID
and bia_panels.ID = bia_panels.project_id
join condition is missing in your select query, this should be added like
JOIN bia_projects ON bia_clients.id = bia_projects.client_id and bia_panels.ID = bia_panels.project_id
following query should give right output
SELECT sign_id, value, left(sign_id, 3) AS city_ID ,
bia_clients.id AS 'client id', bia_projects.id AS proj_id , bia_cities.id
FROM bia_panels
JOIN bia_clients ON bia_panels.value = bia_clients.name
JOIN bia_projects ON bia_clients.id = bia_projects.client_id and bia_panels.ID = bia_panels.project_id
JOIN bia_cities ON bia_projects.city_id = bia_cities.id WHERE bia_panels.value<>'' AND bia_panels.project_id = '000' ORDER BY value
I would little bit reorganize your query into UPDATE query:
UPDATE bia_panels p, bia_clients c, bia_projects t
SET p.project_id=t.id
WHERE p.value=c.name
AND t.client_id=c.id
AND p.project_id=''

How to write LEFT OUTER JOIN on the same table in jOOQ?

how to write following SQL using jOOQ?
SELECT *
FROM food_db_schema.tblCategory AS t1
LEFT OUTER JOIN food_db_schema.tblCategory AS t2 ON t1.category_id = t2.parent_id
WHERE t2.parent_id IS NULL
AND t1.heartbeat = "ALIVE";
database is mySQL
flesk's answer depicts nicely how this can be done with jOOQ 1.x. A self-join using aliasing is more or less equivalent to a regular join using aliasing as described in the manual:
https://www.jooq.org/doc/latest/manual/sql-building/table-expressions/aliased-tables/
In the upcoming version 2.0, aliasing will be made less verbose and more type-safe. Hence flesk's solution could be simplified as such:
// Type-safe table aliasing:
TblCategory t1 = TBLCATEGORY.as("t1");
TblCategory t2 = TBLCATEGORY.as("t2");
Record record = create.select()
.from(t1)
// t1 and t2 give access to aliased fields:
.leftOuterJoin(t2).on(t1.CATEGORY_ID.equal(t2.PARENT_ID))
.where(t2.PARENT_ID.isNull())
.and(t1.HEARTBEAT.equal("ALIVE"));
I have also described a more complex example for a self-join here:
http://blog.jooq.org/jooq-meta-a-hard-core-sql-proof-of-concept/
Maybe
SELECT *
FROM food_db_schema.tblCategory AS t1
WHERE t1.category_id IS NULL
AND t1.heartbeat = "ALIVE";
, but are you sure t2.parent_id is both supposed to be NULL and equal to t1.category_id?
EDIT:
Then something like
Table<TblCategoryRecord> t1 = TBLCATEGORY.as("t1");
Table<TblCategoryRecord> t2 = TBLCATEGORY.as("t2");
Field<Integer> t1CategoryId = t1.getField(TblCategory.CATEGORY_ID);
Field<String> t1Heartbeat = t1.getField(TblCategory.HEARTBEAT);
Field<Integer> t2ParentId = t2.getField(TblCategory.PARENT_ID);
Record record = create.select().from(t1)
.leftOuterJoin(t2).on(t1CategoryId.equal(t2ParentId))
.where(t2ParentId.isNull())
.and(t1Heartbeat.equal("ALIVE"));
depending on what the generated classes, properties and meta-model objects are called.

MySQL - UPDATE query based on SELECT Query

I need to check (from the same table) if there is an association between two events based on date-time.
One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events.
If the first event completes before the second event then I would like to link them up.
What I have so far is:
SELECT name as name_A, date-time as end_DTS, id as id_A
FROM tableA WHERE criteria = 1
SELECT name as name_B, date-time as start_DTS, id as id_B
FROM tableA WHERE criteria = 2
Then I join them:
SELECT name_A, name_B, id_A, id_B,
if(start_DTS > end_DTS,'VALID','') as validation_check
FROM tableA
LEFT JOIN tableB ON name_A = name_B
Can I then, based on my validation_check field, run a UPDATE query with the SELECT nested?
You can actually do this one of two ways:
MySQL update join syntax:
UPDATE tableA a
INNER JOIN tableB b ON a.name_a = b.name_b
SET validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here
ANSI SQL syntax:
UPDATE tableA SET validation_check =
(SELECT if(start_DTS > end_DTS, 'VALID', '') AS validation_check
FROM tableA
INNER JOIN tableB ON name_A = name_B
WHERE id_A = tableA.id_A)
Pick whichever one seems most natural to you.
UPDATE
`table1` AS `dest`,
(
SELECT
*
FROM
`table2`
WHERE
`id` = x
) AS `src`
SET
`dest`.`col1` = `src`.`col1`
WHERE
`dest`.`id` = x
;
Hope this works for you.
Easy in MySQL:
UPDATE users AS U1, users AS U2
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
If somebody is seeking to update data from one database to another no matter which table they are targeting, there must be some criteria to do it.
This one is better and clean for all levels:
UPDATE dbname1.content targetTable
LEFT JOIN dbname2.someothertable sourceTable ON
targetTable.compare_field= sourceTable.compare_field
SET
targetTable.col1 = sourceTable.cola,
targetTable.col2 = sourceTable.colb,
targetTable.col3 = sourceTable.colc,
targetTable.col4 = sourceTable.cold
Traaa! It works great!
With the above understanding, you can modify the set fields and "on" criteria to do your work. You can also perform the checks, then pull the data into the temp table(s) and then run the update using the above syntax replacing your table and column names.
Hope it works, if not let me know. I will write an exact query for you.
UPDATE
receipt_invoices dest,
(
SELECT
`receipt_id`,
CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat
FROM
receipt
WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total
AND vat_percentage = 12
) src
SET
dest.price = src.witoutvat,
dest.amount = src.witoutvat
WHERE col_tobefixed = 1
AND dest.`receipt_id` = src.receipt_id ;
Hope this will help you in a case where you have to match and update between two tables.
I found this question in looking for my own solution to a very complex join. This is an alternative solution, to a more complex version of the problem, which I thought might be useful.
I needed to populate the product_id field in the activities table, where activities are numbered in a unit, and units are numbered in a level (identified using a string ??N), such that one can identify activities using an SKU ie L1U1A1. Those SKUs are then stored in a different table.
I identified the following to get a list of activity_id vs product_id:-
SELECT a.activity_id, w.product_id
FROM activities a
JOIN units USING(unit_id)
JOIN product_types USING(product_type_id)
JOIN web_products w
ON sku=CONCAT('L',SUBSTR(product_type_code,3), 'U',unit_index, 'A',activity_index)
I found that that was too complex to incorporate into a SELECT within mysql, so I created a temporary table, and joined that with the update statement:-
CREATE TEMPORARY TABLE activity_product_ids AS (<the above select statement>);
UPDATE activities a
JOIN activity_product_ids b
ON a.activity_id=b.activity_id
SET a.product_id=b.product_id;
I hope someone finds this useful
UPDATE [table_name] AS T1,
(SELECT [column_name]
FROM [table_name]
WHERE [column_name] = [value]) AS T2
SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];
You can update values from another table using inner join like this
UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];
Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/
or you can use select as subquery to do this
UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];
query explained in details here http://www.voidtricks.com/mysql-update-from-select/
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
For same table,
UPDATE PHA_BILL_SEGMENT AS PHA,
(SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG
FROM PHA_BILL_SEGMENT
GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
HAVING REG > 1) T
SET PHA.BILL_DATE = PHA.BILL_DATE + 2
WHERE PHA.BILL_ID = T.BILL_ID;
I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by #sibaz.
Finally I solved it using the below queries:
The select query is saved in a temp table
IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
DROP TABLE #New_format_donor_temp;
select *
into #New_format_donor_temp
from DONOR_EMPLOYMENTS
where DONOR_ID IN (
1, 2
)
-- Test New_format_donor_temp
-- SELECT *
-- FROM #New_format_donor_temp;
The temp table is joined in the update query.
UPDATE de
SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
FROM DONOR_EMPLOYMENTS AS de
INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
WHERE
de.DONOR_ID IN (
3, 4
)
I not very experienced with SQL please advise any better approach you know.
Above queries are for MySql server.
if you are updating from a complex query. The best thing is create temporary table from the query, then use the temporary table to update as one query.
DROP TABLE IF EXISTS cash_sales_sums;
CREATE TEMPORARY TABLE cash_sales_sums as
SELECT tbl_cash_sales_documents.batch_key, COUNT(DISTINCT tbl_cash_sales_documents.cash_sale_number) no_of_docs,
SUM(tbl_cash_sales_documents.paid_amount) paid_amount, SUM(A.amount - tbl_cash_sales_documents.bonus_amount - tbl_cash_sales_documents.discount_given) amount,
SUM(A.recs) no_of_entries FROM
tbl_cash_sales_documents
RIGHT JOIN(
SELECT
SUM(
tbl_cash_sales_transactions.amount
)amount,
tbl_cash_sales_transactions.cash_sale_document_id,
COUNT(transaction_id)recs
FROM
tbl_cash_sales_transactions
GROUP BY
tbl_cash_sales_transactions.cash_sale_document_id
)A ON A.cash_sale_document_id = tbl_cash_sales_documents.cash_sale_id
GROUP BY
tbl_cash_sales_documents.batch_key
ORDER BY batch_key;
UPDATE tbl_cash_sales_batches SET control_totals = (SELECT amount FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key LIMIT 1),
expected_number_of_documents = (SELECT no_of_docs FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key),
computer_number_of_documents = expected_number_of_documents, computer_total_amount = control_totals
WHERE batch_key IN (SELECT batch_key FROM cash_sales_sums);
INSERT INTO all_table
SELECT Orders.OrderID,
Orders.CustomerID,
Orders.Amount,
Orders.ProductID,
Orders.Date,
Customer.CustomerName,
Customer.Address
FROM Orders
JOIN Customer ON Orders.CustomerID=Customer.CustomerID
WHERE Orders.OrderID not in (SELECT OrderID FROM all_table)