简体   繁体   中英

Return an entry from a table based on criteria, which is not in another table

I need help with a query and i cant figure out how to make it work.

Table1

uid | G | L
------------ 
cde   2   1
fgk   1   2
kgl   2   1

Table2

uid1 |uid2
-----------
abc    cde
fgk    cde
mnm    kgl

I have a known uid which is

 uid | G | L
 -----------
 abc   1   2

and i must match this uid with one from Table1

My query for this is :

SELECT * FROM Table1 WHERE G=2 AND L=1 ORDER BY RAND() LIMIT 1

This will return:

cde   2   1
kgl   2   1

The query that i am looking for must return only kgl because cde is already paired with abc in Table2

Any ideas?

UPDATE : With some tweaking i have come up with this query:

    SELECT uid FROM table1 AS t1 
    WHERE G = 1 AND L = 2 AND NOT EXISTS 
    (SELECT * FROM table2 AS t2 
    WHERE (t1.uid = t2.uid1 OR t1.uid=t2.uid2) AND (t2.uid1 = 'abc' OR t2.uid2 = 'abc'))

You can do it using NOT EXISTS :

SELECT uid, G, L
FROM Table1 AS t1
WHERE G = 2 AND L = 1 
      AND NOT EXISTS (SELECT 1 
                      FROM Table2 AS t2
                      WHERE t1.uid = t2.uid2 AND t2.uid1 = 'abc')

Demo here

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