我正面临一种情况,需要帮助。我有两个表:
用户:
-
user_id
,fname
,lname
,email
.
user_timesheet:
-
time_id
,user_id
,month
,state
,date
.
用户要将时间添加到user_time
状态为“否”的表,并在月底他们提交更改状态 ="is"的时间,假设月份是 JUNE
我想编写一个查询,将所有根本没有添加时间的用户和添加了时间但尚未提交 JUNE 的用户。
这是我的查询。
SELECT user_timesheet.time_id, user_timesheet.user_id,
user_timesheet.month, user_timesheet.`state`,
`user`.user_id, `user`.fname, `user`.lname,
`user`.email
FROM user LEFT JOIN
user_timesheet ON user.user_id=user_timesheet.user_id
WHERE (
user_timesheet.state = 'no' OR
user_timesheet.state IS NULL)
AND (
user_timesheet.month = 'june' OR
user_timesheet.month IS NULL)
GROUP BY user.user_id
结果将所有在 6 月添加时间但已提交的用户以及自加入以来从未添加时间的用户带到系统中。但是,它不会带来在上个月添加时间或提交时间但在 6 月份根本没有添加时间的用户。
最佳答案
在 where 子句中将过滤器放在 ON 子句中,而不是 (a = x or a is null)。这将删除不匹配的记录,但保留左连接的性质。
要将“无”状态视为不存在的行,将其从左连接中过滤掉:
SELECT user_timesheet.time_id, user_timesheet.user_id,
user_timesheet.month, user_timesheet.`state`,
`user`.user_id, `user`.fname, `user`.lname,
`user`.email
FROM user
LEFT JOIN user_timesheet
-- Eliminate users who have submitted 'no'
-- For June
ON user.user_id=user_timesheet.user_id
-- Turn 'no' status into null record
AND user_timesheet.state <> 'no'
AND user_timesheet.month = 'june'
-- If there is no row in user_timesheet
-- It means that
-- a) There was not any
-- b) There was a 'no' status
WHERE user_timesheet.user_id is null
GROUP BY user.user_id
注意:我不知道MySql中的注释标记是什么。它是 -- 在 Sql Server 中,所以在尝试查询之前删除这些行。
关于mysql LEFT JOIN 选择查询结果有限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033133/