SQL查询约束JOIN LEFT表

时间:2018-03-10 11:34:53

标签: mysql sql

我想限制查询的返回,而我约束的值来自JOIN LEFT。我的方法很难失败。

表格userverification

+----+------------+
| id | first_name |
+----+------------+
|  1 | Alex       |
|  2 | Marc       |
|  3 | Cath       |
+----+------------+

+----+---------+-------------+--------+
| id | user_id | verified_at | status |
+--------------+-------------+--------+
|  1 | 1       | 2018-01-02  | done   |
|  2 | 2       | (NULL)      | open   |
|  3 | 3       | 2018-02-02  | done   |
|  4 | 4       | 2018-01-02  | done   |
|  5 | 5       | (NULL)      | open   |
|  6 | 6       | 2018-02-04  | done   |
|  7 | 7       | (NULL)      | open   |
+----+---------+-------------+--------+

以下是不限制verified_at日期的初始查询

SELECT

  u.id,
  u.first_name,
  UNIX_TIMESTAMP(v.verified_at) as verified_at,

  FROM users as u

  LEFT JOIN verification as v on (v.user_id = u.id and v.status = 'done')

  group by u.id

数据库架构和此查询尚未由我完成。就个人而言,我认为如果列状态始终是“完成”的话。设置日期时有点多余。但那就是目前的情况。

我的第一个问题是关于查询的v.status = 'done'部分。它似乎没有做任何事情,因为查询允许所有用户传递给返回。不仅是状态已完成的用户。那么这个constain背后的想法是什么?

第二次,我尝试设法过滤某个验证日期。我尝试了显而易见的事实:

SELECT

  u.id,
  u.first_name,
  UNIX_TIMESTAMP(v.verified_at) as verified_at,

  FROM users as u

  LEFT JOIN verification as v on (v.user_id = u.id and v.status = 'done' and v.verified_at >= '2018-01-01')

  group by u.id

哪个不过滤返回。 v.verified_at IS NOT NULL也没有。

我还尝试将其添加到WHEREHAVING,一直向我提供有关未定义列的提醒。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先,您不需要group by

以下内容列出了所有具有验证日期的用户(如果有):

SELECT u.id, u.first_name, UNIX_TIMESTAMP(v.verified_at) as verified_at,
FROM users u LEFT JOIN
     verification v 
     ON v.user_id = u.id and v.status = 'done';

如果您只想要“完成”的用户,请将JOINLEFT JOIN更改为INNER JOIN

SELECT u.id, u.first_name, UNIX_TIMESTAMP(v.verified_at) as verified_at,
FROM users u INNER JOIN
     verification v 
     ON v.user_id = u.id and v.status = 'done';