2017-07-15 59 views
0

這個問題是關於這一個:Joining multiple tables to get NOT EQUAL values in MySQL更換用戶名的ID JOIN在MySQL

我想延長下面的查詢:

SELECT 
    d.dataid, 
    d.colors, 
    u.userid, 
    u.username 
FROM 
    users u 
     CROSS JOIN 
    datas d 
WHERE 
    (u.userid , d.dataid) NOT IN (SELECT 
      c.userid, c.dataid 
     FROM 
      collections c) 
     AND u.userid = 1 

對於這個數據樣本:

table datas     table users   table collections 
dataid | colors | addedby userid | username collectionid | userid | dataid 
-------------------------- ------------------- ------------------------------ 
    1 | blue | 1  1 | Brian   1  | 1 | 1 
    2 | red  | 1  2 | Jason   2  | 2 | 3 
    3 | green | 2  3 | Marie   3  | 1 | 3 
    4 | yellow | 3        4  | 3 | 2 

預計結果:

for Brian   
dataid | colors | userid | username 
----------------------------------- 
    2 | red | 1 | Brian 
    4 | yellow | 1 | Marie 

for Jason 
dataid | colors | userid | username 
----------------------------------- 
    1 | blue | 2 | Brian 
    2 | red | 2 | Brian 
    4 | yellow | 2 | Marie 

添加了「addedby」行,它繼承了用戶的用戶標識。 目前我的查詢替換用戶的用戶標識,而不是用用戶名從數據中添加。 我真的需要從數據庫中替換userid,而不是來自用戶的userid。 :-)

有沒有人有線索如何解決這個問題?

在此先感謝!

歡呼聲

+1

非常混亂。但是好像你需要第二次加入'users'表。 – dnoeth

回答

1

只需再次加入用戶表與數據表。並在輸出中使用此連接的用戶名。

SELECT 
    d.dataid, 
    d.colors, 
    uo.userid, 
    uo.username 
FROM 
    users u 
     CROSS JOIN 
    datas d 
INNER JOIN 
    users uo 
ON d.added_by = uo.id 

WHERE 
    (u.userid , d.dataid) NOT IN (SELECT 
      c.userid, c.dataid 
     FROM 
      collections c) 
     AND u.userid = 1 

而且我相信,你甚至可以編寫查詢這樣

SELECT u.userid, u.username, d.dataid, d.colors 

FROM username u 
INNER JOIN datas d 
    ON u.userid = d.addedby 

WHERE d.dataid NOT IN (
    SELECT dataid 
    FROM collections 
    WHERE userid = 1 
) 
+0

短'甜!非常感謝這個簡單的工作解決方案:-) – GePu