简体   繁体   中英

mysql opposite query of a join

I have 2 tables. 2nd tables 2 PK referenced as 2FK from 1st table which are also 2 PK. i want to pull out the records that do not match?

The following query matches the records that match base on these 2 keys. This returns 3828 rows. how do i do the opposite>

SELECT * 
FROM hdb.addressesconsultants a
join orderconsultants o where a.CONSULTANT = o.CONSULTANT and a.ORDERNO = o.ORDERNO

below returns 3837 rows.

SELECT *  FROM hdb.addressesconsultants a

@munguea05

this did what i was after, it returned 9 rows which was the discrepancy, however i have 4044 rows in orderconsultants how do i resolve that or grab the rows that do not match to addressconsultants from orderconsutlants ?

How can I delete these rows?

SELECT o.*
FROM hdb.orderconsultants o
LEFT OUTER JOIN addressesconsultants a 
ON a.CONSULTANT = o.CONSULTANT AND a.OrderNo = o.OrderNo
WHERE a.CONSULTANT is NULL and a.OrderNo is NULL

You want those without an order? Use a left join and consider only those that have NULL on the left joined table

SELECT * 
FROM hdb.addressesconsultants a
LEFT JOIN orderconsultants o 
ON a.CONSULTANT = o.CONSULTANT and a.ORDERNO = o.ORDERNO
WHERE
    o.CONSULTANT IS NULL

It depends if you want results from just one table that don't match, or results from both tables that don't match.

This gives you one, if you need the results from both just do the opposite.

SELECT *
FROM hdb.addressesconsultants a (NOLOCK)
LEFT OUTER JOIN orderconsultants o (NOLOCK)
ON A.consultant = o.Consultant AND a.OrderNo = o.OrderNo
WHERE o.Consultant is NULL and O.OrderNo is NULL
SELECT a.* 
FROM hdb.addressesconsultants a
left join orderconsultants o where a.CONSULTANT = o.CONSULTANT and a.ORDERNO = o.ORDERNO
where o.CONSULTANT is null

This will show any entry for which there was an entry in addressesconsultants, but no corresponding entry in orderconsultants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM