两次连接两个表并返回重复的列名

时间:2013-01-18 09:52:41

标签: mysql codeigniter

假设我有两个表USER和MESSAGE

USER -  id,name
MESSAGES - id,message_from,message_to,message_message

所以为了加入我使用这个合作

SELECT m.*,u1.*,u2.* FROM MESSAGES m
    INNER JOIN USER as u1
       ON(m.message_from = u1.id)  
    INNER JOIN USER as u2
       ON(m.message_to = u2.id)

所以现在当我在codeigniter中打印出结果时,它没有用户message_to的用户数据。

我猜即使它返回两个用户的数据,那么它应该有一些前缀来区分

那我该怎么做呢?

谢谢和问候

2 个答案:

答案 0 :(得分:1)

使用别名:

SELECT m.id,
    u1.id as u1id,
    u1.name as u1name,
    u2.id as u2id,
    u2.name as u2name
FROM MESSAGES m
INNER JOIN USER as u1
    ON(m.message_from = u1.id)  
INNER JOIN USER as u2
    ON(m.message_to = u2.id)

答案 1 :(得分:1)

最好避免使用SELECT *语法。

我建议您指定要返回的列,并为名称不唯一的列提供别名。

SELECT m.id AS MessageId,m.message_from,m.message_to,m.message_message,
    u1.id AS FromId, u1.name AS FromName,
    u2.id AS ToId,u2.name AS ToName FROM MESSAGES m
INNER JOIN USER as u1 ON(m.message_from = u1.id)  
INNER JOIN USER as u2 ON(m.message_to = u2.id)