2013-10-16 41 views
0

我試圖根據表中的member_id,parent_idsponsor_id表從表「member」中提取parent_name和sponsor_name。加入兩個Mysql表來獲取多列的名稱

我試過下面的查詢,但我不知道爲什麼它不起作用。

SELECT mt.member_id, mt.parent_id, mt.sponsor_id, mt.member_name, m.member_name as parent_name , m1.member_name as sponsor_name 
FROM `member_tree` mt 
LEFT JOIN `member` m ON mt.parent_id = m.member_id 
LEFT JOIN `member` m1 ON mt.sponsor_id = m1.member_id 
WHERE mt.`member_id` IN (1000015,1000016,1000017,1000018,1000019,1000020,1000021,1000022,1000023,1000024,1000025,1000026,1000027,1000028,1000029,1000030) 

Mysql Table

謝謝。

+0

嘗試m.member_id = mt.parent_id。也請先試着用單行來理解查詢 – Nes

回答

1

此查詢工作正常,你可以檢查它在小提琴http://sqlfiddle.com/#!2/499e95/1

只要確保

你有沒有在這兩個表MEMBER_NAME領域,因爲你已經寫mt.member_nameMT是指member_tree

如果你沒有在member_tree標籤成員名稱le從小提琴使用此查詢http://sqlfiddle.com/#!2/5d2bd/1

SELECT mt.member_id, mt.parent_id, mt.sponsor_id, m.member_name, 
m1.member_name as parent_name , m2.member_name as sponsor_name 
FROM `member_tree` mt 
LEFT JOIN 
`member` m ON mt.member_id = m.member_id 
LEFT JOIN 
`member` m1 ON mt.parent_id = m1.member_id 
LEFT JOIN 
`member` m2 ON mt.sponsor_id = m2.member_id 
WHERE mt.`member_id` 
IN (1000015,1000016,1000017,1000018,1000019,1000020,1000021,1000022,1000023,1000024,1000025,100 0026,1000027,1000028,1000029,1000030) 
+0

謝謝。有效。 :) –

+0

歡迎。快樂是我的全部。 –

0

對我來說看起來不錯 - 儘管我可能會這樣寫。

0

您能否確保parent_id和sponsor_id存在外鍵。如果不是,您可以檢查member_ids 1000007到1000014是否存在於成員表中。