mysql LEFT JOIN 选择查询结果有限

标签 mysql sql join where-clause

我正面临一种情况,需要帮助。我有两个表:

用户:

  • 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/

相关文章:

mysql - 如何创建一个数据库来接收来自其他数据库的数据、手动输入和数据导出以创建 Web 仪表板?

php - 获取 mysql 数据并创建其页面

sql - 在日期不同时加入日期表

mysql - mysql 中 join_buffer_size 的推荐最大值是多少?

mysql - Left 排除 MySQL 中的 JOIN

mysql - Concat/内连接 MySQL

mysql - Oracle sqlldr - 处理输入数据集中的空值

java.sql.SQLException : Incorrect string value: '\xF0\x9F\x98\x8F' for column 'tweetcontent' at row 1 异常

mysql - 为前 n 个不同的元素选择行(两列或更多列)

Mysql ( Doctrine ) - 计算计数 > X 的内连接