2016-10-10 59 views
0

我有兩個表加入一個是category表字段多在同一列

id , name, created_by, created_date, modify_by, modify_date, status 

(請注意CREATED_BY & modify_by將有來自用戶表的用戶的ID)

和其他表user與列

id, name, role and many more 

我必須在網頁上列出與創建新的用戶的名稱類別和那些誰也修改

我使用下面的SQL查詢來獲取CREATED_BY用戶名,也modify_by用戶名顯示在列表

BEGIN 
    SELECT cat.id,cat.name, cate.name as parentname, cat.parent_id, 
    cat.created_by, cat.created_date, cat.modify_by, cat.modify_date, 
    user.firstname 
    FROM `category`as cat  
    INNER JOIN `user` ON cat.created_by = user.id 
    LEFT JOIN category as cate ON cate.id = cat.parent_id; 
END 

我應該添加到此查詢來獲取amemodifier用戶類別n從它的id可以不同於creator id?

還是我必須編寫單獨的查詢獲取修飾名稱?

+0

請修復您的格式。 –

+3

您正在使用哪些DBMS? –

回答

0

如果我沒有錯,你需要加入USER表兩次

SELECT cat.id, 
     cat.NAME, 
     cat.NAME AS parentname, 
     cat.parent_id, 
     cat.created_by, 
     cat.created_date, 
     cat.modify_by, 
     cat.modify_date, 
     c.firstname AS created_user, 
     m.firstname AS modified_user 
FROM categoryas cat 
     LEFT JOIN USER c 
       ON cat.created_by = c.id 
     LEFT JOIN USER m 
       ON cat.modify_by = m.id; 

如果created_by柱將永遠NULL,那麼你可以改變LEFT JOIN USER cINNER JOIN USER c

+0

它工作謝謝every1 – Learner

0

只需添加另一個用戶加入不同的表別名就可以了。

SELECT cat.id,cat.name, cate.name as parentname, cat.parent_id, 
cat.created_by, cat.created_date, cat.modify_by, cat.modify_date, 
creator.firstname creator_name, midifier.firstname modifier_name FROM 
categoryas cat INNER JOIN user creator ON 
cat.created_by = creator.id 
INNER JOIN user midifier ON 
cat.modify_by = midifier.id 
LEFT JOIN category as cate ON cate.id = cat.parent_id; 
+0

不,它不會工作,我已經嘗試過在這裏張貼;然後它只給出一個與之前輸出相同的類別列表 – Learner

+0

@Humbledust'modify_by'是否存儲所有修飾符ID?像'1,2,3'? – amow

+0

它只是存儲修改時刻登錄到帳戶的用戶標識; ID是通過使用隱藏字段的會話傳遞的 – Learner

0

您需要與該表具有不同別名的兩個連接。

BEGIN 
    SELECT cat.id,cat.name, cate.name as parentname, cat.parent_id, 
    cat.created_by, cat.created_date, cat.modify_by, cat.modify_date, 
    user.firstname, modifiedUser.firstname as modifiedUser 
    FROM `category`as cat 
    INNER JOIN `user` ON cat.created_by = user.id 
    LEFT JOIN category as cate ON cate.id = cat.parent_id; 
    JOIN `user`modifiedUser ON cate.modify_by = user.id 
END