MySQL选择一个表中的行而不是另一个表中的特定日期

时间:2017-02-27 07:42:57

标签: mysql join

我有两个表格个人和工作人员登录时间如下所述。我想取得那些在特定日期没有登录的工作人员。

individuals
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1  | Smith | 1234567897 |
+----+------+--------------+
| 2  | David | 9874561237 |
+----+------+--------------+
| 3  | John | 7778889991 |
+----+------+--------------+

staff_login_times
+----+------+--------------+
| id | individual_id | login_date |
+----+------+--------------+
| 1  | 2             | 2017-02-27 |
+----+------+--------------+
| 2  | 1             | 2017-02-26 |
+----+------+--------------+
| 3  | 2             | 2017-02-26 |
+----+------+--------------+
| 4  | 3             | 2017-02-26 |
+----+------+--------------+

如何找出27日没有出现的人

Result
+----+------+--------------+
| id | name  | phone_number |
+----+------+--------------+
| 1  | Smith | 1234567897   |
+----+------+--------------+
| 3  | John  | 7778889991   |
+----+------+--------------+

我已经尝试过查询:

SELECT *
FROM individuals
LEFT JOIN staff_login_times ON individuals.id = staff_login_times.individual_id
WHERE staff_login_times.individual_id IS NULL
  AND staff_login_times.login_date = '2017-02-27'

4 个答案:

答案 0 :(得分:1)

只需稍加改动,使用你的条件和连接语句: -

SELECT *
FROM individuals
LEFT JOIN staff_login_times ON individuals.id = staff_login_times.individual_id AND staff_login_times.login_date = '2017-02-27'
WHERE staff_login_times.individual_id IS NULL

答案 1 :(得分:0)

您不需要加入

试试这个

select * from individuals 
where id not in 
(select individual_id from staff_login_times where login_date = '2017-02-27');

答案 2 :(得分:0)

我希望这会有所帮助:

SELECT a.id, a.`name`, a.phone_number, b.login_date FROM individuals a LEFT JOIN 
staff_login_times b on a.id = b.individual_id WHERE b.login_date <> "2017-02-27";

答案 3 :(得分:-1)

您可以使用的另一个选项是展开where条件,而不是LEFT JOIN

  SELECT individuals.id ,individuals.name FROM individuals ,staff_login_times WHERE 
staff_login_times.login_date = '2017-02-27'
AND staff_login_times.individual_id  != individuals.id ;