SQL - 选择查询
这里是我的模拟数据SQL - 选择查询
Table 1 Table 2
Column 1 Column 2 Column 1 Column 2
111 AAA 111 AAA
111 BBB 111 BBB
222 AAA 111 CCC
... 222 AAA
...
我想表2表1的“孩子”(列2),这是在表1中没有在这种情况下,我需要'111 CCC'
。
我会用CONCAT。我读到你的问题的方式,你不只是检查表1中的CCC,而是想知道111 AND CCC的组合是否在表1中。你可以这样做:
SELECT column1, column2
FROM table2
WHERE CONCAT(column1, column2)
NOT IN
(SELECT CONCAT(column1, column2)
FROM table1)
糟糕的主意,因为你不能使用索引。更好的是与这两列正确连接 –
你是什么意思的索引? – kbball
为了优化该查询,OP应该在'INDEX(col1,col2)'上使用'CONCAT'创建将避免使用索引 –
您可以用WHERE NOT EXISTS
做到这一点很容易:
Select T2.*
From Table2 T2
Where Not Exists
(
Select *
From Table1 T1
Where T1.Column1 = T2.Column1
And T1.Column2 = T2.Column2
)
你可以用 “不” 尝试:
select column1, column2
from table2
where column2 not in (select column2 from table1)
SELECT *
FROM table1 t1
RIGHT JOIN table2 t2
on t1.Col1 = t2.col1
AND t1.Col2 = t2.Col2
WHERE t1.Col1 is NULL
AND t1.Col2 is NULL
不要懒惰,并显示我们的愿望结果。请阅读[** How-to-Ask **](http://*.com/help/how-to-ask) \t \t这里是[** START **](http ://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/),了解如何提高您的问题质量并获得更好的答案。 –
@JuanCarlosOropeza我同意这个问题很懒,因为它显示绝对没有努力,但他确实有一个预期的结果。 – Siyual
@颜色词与格式表不同。 –