[英]mysql LEFT JOIN select query with limited results
我正面临一种情况,需要帮助。 我有两个表:
用户:
user_id
, fname
, lname
, email
。 user_timesheet:
time_id
, user_id
, month
, state
, date
。 用户user_time
状态添加为user_time
表,状态为=“否”,并在月底提交该时间,假设状态为6月,则更改状态为“ yes”。我想编写一个查询来将所有完全没有添加时间的用户和已经添加时间但尚未提交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月份根本没有添加时间的用户。
首先,首先创建一个查询,该查询将在指定时间段内添加时间的所有用户的userId与“ YES”状态=>匹配,您就拥有了所有“良好”用户。 那么您只需要选择不在该列表中的所有用户即可。 您可以在子查询或减号查询中使用“不存在”,“不存在”。
不在中的示例:
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.user_id not in (
select user.user_id
from user inner join user_timesheet ON user.user_id=user_timesheet.user_id
where user_timesheet.state = 'yes'
AND user_timesheet.month = june
)
)
代替where子句中的(a = x或a为null),将您的过滤器放在ON子句中。 这将删除不匹配的记录,但保留左联接的性质。
要将“否”状态视为不存在的行过滤器,请从左联接中滤除它:
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中,因此请在尝试查询之前删除此行。
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
AND user_timesheet.month = 'june' AND user_timesheet.state = 'no'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.