我有一个很大的问题,我不知道发生了什么。这是我的
table1
+-----+-----------------------+--------------+
| id | invoice_number | invoice_date |
+-----+-----------------------+--------------+
| 12 | 12536801244 | 2009-09-23 |
| 38 | 12585302890 | 2009-11-18 |
| 37 | 12584309829 | 2009-11-16 |
| 123 | 12627605146 | 2010-01-06 |
| 191 | 12663105176 | 2010-02-16 |
+-----+-----------------------+--------------+
这是我的第二个
table2
+-----+-----------------------+--------------+
| id | invoice_number | invoice_date |
+-----+-----------------------+--------------+
| 12 | 1t657801244 | 2009-09-23 |
| 20 | 12585302890 | 2009-11-18 |
| 37 | 1ss58430982 | 2009-11-16 |
| 103 | 12627605146 | 2010-01-06 |
| 121 | 12346310517 | 2010-02-16 |
+-----+-----------------------+--------------+
我想要的是,我得到的所有invoice_numbers都不在 table2
这是我的SQL查询。
select t2.invoice_number FROM table1 t1
JOIN table2 t2 ON t2.invoice_number != t1.inovice_number;
但是我得到了不同的结果。任何机构SQL代码有什么问题?
答案 0 :(得分:1)
你为什么不试试:
Select * from Table1
Where Table1.invoice_number NOT IN (select invoice_number from Table2)
答案 1 :(得分:1)
您可以使用LEFT JOIN
。
SELECT t1.invoice_number
FROM table1 t1
LEFT JOIN table2 t2 ON t2.invoice_number = t1.inovice_number
WHERE t2.invoice_number IS NULL
答案 2 :(得分:1)
性能方面,您可以使用Left Join或Not EXIST
尝试使用左连接
Select t2.invoice_number
FROM table1 t1
LEFT JOIN table2 t2 ON
t2.invoice_number = t1.inovice_number AND
t2.invoice_number IS NULL;
尝试不存在
Select t2.invoice_number
FROM table1 t1 Where Not Exist
(
SELECT NULL
FROM table2 t2
WHERE t2.invoice_number = t1.inovice_number
)
尝试使用Not IN
Select t2.invoice_number
FROM table1 t1
Where t1.inovice_number NOT IN
(
SELECT t2.inovice_number
FROM table2 t2
)
答案 3 :(得分:0)
为什么不使用where not exists
?
SELECT *
FROM table1 t1
WHERE NOT EXISTS (SELECT * FROM table2 t2 WHERE t1.invoice_number = t2.invoice_number)
答案 4 :(得分:0)
这不是查询您要查找内容的正确方法。
你可能需要这样的东西:
select invoice_number from table2
where invoice_number not in (select invoice_number from table1)
答案 5 :(得分:0)
select * from table1 where invoice_number NOT EXISTS (select invoice_number FROM table2 WHERE table1.invoice_number = table2.invoice_number);
答案 6 :(得分:0)
select t2.id FROM table1 as t1
INNER JOIN table2 as t2 ON t2.id != t1.id;