连接两个Mysql表来获取多个列的名称

时间:2013-10-16 10:38:41

标签: php mysql sql

我正在尝试根据member_id表中的parent_idsponsor_idmember_tree从表“member”中获取parent_name和sponsor_name。

我尝试了以下查询,但我不知道它为什么不起作用。

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

谢谢。

3 个答案:

答案 0 :(得分:1)

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

中查看

请确保

您是否在表格中都有 member_name字段,因为您已写入 mt.member_name ,并且 mt将指向 member_tree

如果您在member_tree表中没有成员名称,请使用小提琴中的此查询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 )

答案 1 :(得分:0)

看起来对我好 - 虽然我可能会这样写。

答案 2 :(得分:0)

您能否确保parent_id和sponsor_id存在外键。如果没有,你可以检查member_ids 成员表中存在1000007到1000014。