2014-04-13 132 views
2

我已經得到了我在其中要排除特定值(在這個例子中「馬太福音」)查詢SQL查詢排除值

的查詢工作不完美子查詢它:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
    FROM test 
    LEFT JOIN test2 
    ON test.noID=test2.noID 
    WHERE test.SAME = 555 and test.Name NOT IN (
               SELECT * 
               FROM test 
               WHERE test.NAME = "Mat" 
              ) 
    group by SAME , name 
    order by same desc 

這裏舉例:

http://www.sqlfiddle.com/#!2/1f1fb/28

+0

http://www.sqlfiddle.com/#!2/1f1fb/34 – Mihai

+0

這不起作用,因爲如果您的子查詢是'SELECT test.Name FROM',比較'test.Name'和'SELECT *' '它的工作。順便說一句,正如人們建議直接使用'!='或'<>'或'NOT LIKE'來排除沒有子查詢的名稱;) – Ryx5

+0

在你的where子句中嵌套select語句是不好的做法。您應該使用連接並根據where子句中的匹配進行排除。 –

回答

0

你可以做到這一點,如果你想與匹配確切名稱:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
    FROM test 
    LEFT JOIN test2 
    ON test.noID=test2.noID 
    WHERE test.SAME = 555 and test.Name != "Mat" 

group by SAME , name 
    order by same desc 

如果要排除所有包含,則:如果你想排除

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
     FROM test 
     LEFT JOIN test2 
     ON test.noID=test2.noID 
     WHERE test.SAME = 555 and test.Name NOT LIKE '%Mat%' 

    group by SAME , name 
     order by same desc 

始於,則:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
      FROM test 
      LEFT JOIN test2 
      ON test.noID=test2.noID 
      WHERE test.SAME = 555 and test.Name NOT LIKE 'Mat%' 

     group by SAME , name 
      order by same desc 
0

您可以使用NOT LIKEstatement

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
    FROM test 
    LEFT JOIN test2 
    ON test.noID=test2.noID 
    WHERE test.SAME = 555 and test.Name not like 'Mat' 
    group by SAME , name 
    order by same desc 

SQLFiddle

還是<>!=operator

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
    FROM test 
    LEFT JOIN test2 
    ON test.noID=test2.noID 
    WHERE test.SAME = 555 and test.Name <> 'Mat' 
    group by SAME , name 
    order by same desc 

SQLFiddle

+1

作品完美,謝謝! – user3066588

0

您的查詢應該是: -

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb 
    FROM test 
    LEFT JOIN test2 
    ON test.noID=test2.noID 
    WHERE test.SAME = 555 and test.Name NOT IN (
              SELECT NAME 
              FROM test 
              WHERE test.NAME = "Mat" 
             ) 
    group by SAME , name 
    order by same desc 
0

子QUER y不會工作,因爲你在子查詢中給了select *,但在外部查詢中你只有一個單獨的列來匹配哪個是test.Name。如果你將子查詢(SELECT test.Name FROM test WHERE test.NAME =「Mat」)放在一起,那麼整個查詢就可以工作。但順便說一下,這裏不需要子查詢來獲得您想要的結果。