我需要查询帮助,我无法弄清楚如何使它工作。
表1
uid | G | L
------------
cde 2 1
fgk 1 2
kgl 2 1
表2
uid1 |uid2
-----------
abc cde
fgk cde
mnm kgl
我有一个已知的uid
uid | G | L
-----------
abc 1 2
我必须将此uid与 Table1
中的uid相匹配我对此的质询是:
SELECT * FROM Table1 WHERE G=2 AND L=1 ORDER BY RAND() LIMIT 1
这将返回:
cde 2 1
kgl 2 1
我要查找的查询必须仅返回kgl
,因为cde
已与表2
abc
配对
有什么想法吗?
更新:通过一些调整,我提出了这个问题:
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'))
答案 0 :(得分:1)
您可以使用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')