2016-09-20 158 views
0

這裏是我的模擬數據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'

+0

不要懶惰,並顯示我們的願望結果。請閱讀[** How-to-Ask **](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **](http ://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/),瞭解如何提高您的問題質量並獲得更好的答案。 –

+0

@JuanCarlosOropeza我同意這個問題很懶,因爲它顯示絕對沒有努力,但他確實有一個預期的結果。 – Siyual

+1

@顏色詞與格式表不同。 –

回答

0

我會用CONCAT。我讀到你的問題的方式,你不只是檢查表1中的CCC,而是想知道111 AND CCC的組合是否在表1中。你可以這樣做:

SELECT column1, column2 
FROM table2 
WHERE CONCAT(column1, column2) 
NOT IN 
(SELECT CONCAT(column1, column2) 
FROM table1) 
+0

糟糕的主意,因爲你不能使用索引。更好的是與這兩列正確連接 –

+0

你是什麼意思的索引? – kbball

+0

爲了優化該查詢,OP應該在'INDEX(col1,col2)'上使用'CONCAT'創建將避免使用索引 –

0

您可以用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 
) 
0

你可以用 「不」 嘗試:

select column1, column2 
from table2 
where column2 not in (select column2 from table1) 
0
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