如何从一个不存在于另一个表中的表中查找数据?

时间:2015-12-10 04:29:54

标签: mysql database

我有2张桌子,如下所示。如何检查task_detail表中没有哪些data_entry信息。

data_entry
+----+----------+----------+
| id | firstname| lastname |
+----+----------+----------+
| 1  | Anil     | Chaudhari|
+----+----------+----------+
| 2  | Sunil    | Chaudhari|
+----+----------+----------+
| 3  | Pranil   | Chaudhari|
+----+------+--------------+

task_detail
+----+-------+--------------+--------+
| id | de_id | field_name   | amount |
+----+-------+--------------+--------+
| 1  | 1     | firstname    | 0.1    |
+----+-------+--------------+--------+
| 2  | 1     | lastname     | 0.1    |
+----+-------+--------------+--------+

我只想要

data_entry
+----+----------+----------+
| id | firstname|lastnamer |
+----+----------+----------+
| 2  | Sunil    | Chaudhari|
+----+----------+----------+
| 3  | Pranil   | Chaudhari|
+----+------+--------------+

5 个答案:

答案 0 :(得分:2)

也许这会奏效:

SELECT * FROM data_entry 
WHERE  id NOT IN (SELECT  de_id FROM task_detail) 

答案 1 :(得分:2)

在大多数情况下,连接速度比子查询参考速度快sql join vs sub query,因此您也可以使用左连接:

select de.* from data_entry de left join task_detail td on td.de_id = de.id where td.id is null

答案 2 :(得分:1)

使用子查询。

SELECT * FROM data_entry WHERE id NOT IN (SELECT de_id FROM task_detail)

使用左连接

SELECT de.* FROM data_entry de LEFT JOIN task_detail td ON de.id=td.de_id WHERE td.field_name IS NULL

答案 3 :(得分:1)

你可以试试这个:

SELECT * FROM data_entry 
WHERE NOT EXISTS
(SELECT * FROM task_detail WHERE de_id=data_entry.id) 

答案 4 :(得分:0)

select t1.* from data_entry t1 join data_entry t2 on t1.id = t2.de_id where t1.id !=  t2.de_id