简体   繁体   English

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

[英]MySQL combine two table fields by matching their id

For example I have created two tables. 例如,我创建了两个表。

Table One: t5zgu_property_message 表一: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

Table Two: t5zgu_users 表二:t5zgu_users

id username

42 Jack
57 Rocky

I want output like this way: 我想要这样的输出:

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

My current query is: 我当前的查询是:

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

This query is working perfect with msg_from and getting right output but I don't know how to write for msg_to . 此查询与msg_from完美配合并获得正确的输出,但我不知道如何为msg_to编写。

Any ideas or suggestions? 有什么想法或建议吗? Thanks. 谢谢。

All you need is to join the users table again: 您所需要做的就是再次加入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

Or the same thing using JOIN syntax: 或使用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

Try the following statement: 请尝试以下语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM