MySQL通过匹配它们的id来组合两个表字段

时间:2013-08-22 09:08:04

标签: php mysql sql

例如,我创建了两个表。

表一:t5zgu_property_message

msg_from msg_to subject message

57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
42       42     xxxxx   xxxxxx

表二:t5zgu_users

id username

42 Jack
57 Rocky

我想要这样输出:

msg_from msg_to subject message msg_from  msg_to

57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
42       42     xxxxx   xxxxxx  Jack      Jack

我目前的查询是:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from
FROM 
    t5zgu_property_message,
        t5zgu_users
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id

ORDER BY t5zgu_property_message.id DESC

此查询与 msg_from 完美配合并获得正确的输出,但我不知道如何为 msg_to 撰写。

有任何想法或建议吗?感谢。

2 个答案:

答案 0 :(得分:5)

您只需要再次加入users表格:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message,
    t5zgu_users,
    t5zgu_users t5zgu_users2
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id
    AND
    t5zgu_property_message.msg_to = t5zgu_users2.id

ORDER BY t5zgu_property_message.id DESC

使用JOIN语法的相同内容:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message
    JOIN t5zgu_users ON t5zgu_property_message.msg_from = t5zgu_users.id
    JOIN t5zgu_users t5zgu_users2 ON t5zgu_property_message.msg_to = t5zgu_users2.id
ORDER BY t5zgu_property_message.id DESC

答案 1 :(得分:0)

请尝试以下声明:

SELECT 
        p.id,
        p.msg_from,
        p.msg_to,
        p.subject,
        p.message,
        u1.username as msg_from
        u2.username as msg_to
FROM 
    t5zgu_property_message p LEFT JOIN 
        t5zgu_users u1 ON u1.id = p.msg_from
    LEFT JOIN t5zgu_users u2 ON u2.id = p.msg_to

ORDER BY p.id DESC