0

我必须表:USERSDATA。每个userfromUSERS可以有一个,multiple rowsonDATA也可以是 any。

我还想选择没有对应关系的usersfrom ,但以下查询省略了它们。我应该如何修改它?USERSDATA

SELECT USERS.id,
       USERS.email,
       USERS.active,
       USERS.last_alert,
       DATA.active,
       DATA.active_from
FROM USERS
JOIN DATA
WHERE DATA.id_user = USERS.id
    AND DATA.active = 1
ORDER BY USERS.id ASC

DATA.id_user包含USERS.id.

4

3 回答 3

3

您应该使用 LEFT JOIN 而不是 INNER JOIN

SELECT
    USERS.id,
    USERS.email,
    USERS.active,
    USERS.last_alert,
    DATA.active,
    DATA.active_from
FROM USERS
    LEFT JOIN DATA ON (
        DATA.id_user = USERS.id AND DATA.active = 1
    )
ORDER BY USERS.id ASC
于 2013-09-26T13:27:25.930 回答
0

做外连接

SELECT USERS.id,
       USERS.email,
       USERS.active,
       USERS.last_alert,
       DATA.active,
       DATA.active_from
FROM DATA
LEFT OUTER JOIN USERS
WHERE DATA.id_user = USERS.id
    AND DATA.active = 1
ORDER BY USERS.id ASC
于 2013-09-26T13:25:24.440 回答
0

将其重写为LEFT JOIN应该包括那些行,但不可用的值将变为NULL那时

SELECT USERS.id,
       USERS.email,
       USERS.active,
       USERS.last_alert,
       DATA.active,
       DATA.active_from
FROM USERS
LEFT JOIN DATA ON USERS.id = DATA.id_user AND DATA.active = 1
ORDER BY USERS.id ASC
于 2013-09-26T13:26:04.570 回答