MySQL Select rows that from table01 that doesn't exist on table02 [duplicate]

廉价感情. 提交于 2021-02-17 06:55:26

问题


I have two tables, table03 have 10 rows and table01 have 21 rows, now I want to get rows from table03 where they don't exist in table01, so far I wrote this query but it shows all rows of table03 even some rows doesn't exist on table01.

SELECT T3.`DateAdded`, T3.`Query_name`, T3.`Fund`, T3.`Ticker` 
FROM `table_name03` T3 LEFT JOIN `table_name01` T1 
ON T3.`DateAdded` = T1.`DateAdded` 
AND `T3`.`Query_name` = `T1`.`Query_name` 
AND `T3`.`Fund` = `T1`.`Fund`
AND `T3`.`Ticker` = `T1`.`Ticker`

Table03:

Table01:


回答1:


You are on the right track. You can just add a where condition to filter on unmatched rows:

SELECT T3.DateAdded, T3.Query_name, T3.Fund, T3.Ticker 
FROM table_name03 T3 
LEFT JOIN table_name01 T1 
    ON  T3.DateAdded = T1.DateAdded 
    AND T3.Query_name = T1.Query_name 
    AND T3.Fund = T1.Fund
    AND T3.Ticker = T1.Ticker
WHERE T1.DateAdded IS NULL

You can also use not exists:

SELECT T3.DateAdded, T3.Query_name, T3.Fund, T3.Ticker 
FROM table_name03 T3 
WHERE NOT EXISTS (
    SELECT 1
    FROM table_name01 T1 
    WHERE
        T3.DateAdded = T1.DateAdded 
        AND T3.Query_name = T1.Query_name 
        AND T3.Fund = T1.Fund
        AND T3.Ticker = T1.Ticker
)


来源:https://stackoverflow.com/questions/61110587/mysql-select-rows-that-from-table01-that-doesnt-exist-on-table02

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!