繁体   English   中英

MySQL从一个表中选择行而不在另一个表中选择特定日期

[英]MySQL select rows from one table not in another for specific dates

我有两个表个人和职员登录时间,如下所述。 我想获取在特定日期未登录的人员。

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'

只是很小的变化,使用您的条件和join语句即可:-

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

你不需要加入

尝试这个

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

我希望这有帮助:

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";

您可以使用的另一个选项是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 ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM