2013-09-26 38 views
0

我要表:USERSDATA。每userUSERS可以有一個,多個rowsDATA還要什麼。SQL SELECT與JOIN也沒有對應的記錄上第二個表

我想選擇usersUSERS沒有對應DATA但以下查詢省略它們。我應該如何修改它?

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

回答

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 
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 
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 
相關問題