0

例如,我创建了两个表。

表一: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编写。

有什么想法或建议吗?谢谢。

4

2 回答 2

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
于 2013-08-22T09:11:07.413 回答
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
于 2013-08-22T09:14:37.693 回答