MySQL - 在查询中将用户用户名映射到用户的ID

时间:2010-08-31 00:22:41

标签: sql mysql

我已经完成了一些复杂的SQL查询,但从未通过多个值连接两个表,我不确定它是否可行。

我有以下两个表:

        users
        +-------+----------+
        | u_ID  | username |
        +-------+----------+
        |   1   |  Pablo   |
        +-------+----------+
        |   2   |   Mike   |
        +-------+----------+


        Messages
        +-------+----------+---------+
        | m_ID  | auhor_id | message |
        +-------+----------+---------+
        |   1   |     2    | Heelo5  |
        +-------+----------+---------+
        |   2   |     1    | he4532  |
        +-------+----------+---------+
        |   3   |     2    | he4111  |
        +-------+----------+---------+
        |   4   |     1    | he4538  |
        +-------+----------+---------+

我需要什么SQL查询来获取此表?

    +-------+----------+---------+
    | m_ID  | username | message |
    +-------+----------+---------+
    |   1   |   Mike   | Heelo5  |
    +-------+----------+---------+
    |   2   |  Pablo   | he4532  |
    +-------+----------+---------+
    |   3   |   Mike   | he4111  |
    +-------+----------+---------+
    |   4   |  Pablo   | he4538  |
    +-------+----------+---------+

3 个答案:

答案 0 :(得分:3)

select m.m_ID, u.username, m.message
from Messages m, users u
where m. auhor_id = u.m_ID;

您可能希望WHERE子句中的其他条件指定哪些消息记录。正如我所写,所有消息记录都会显示出来。

答案 1 :(得分:1)

select
 m.m_ID,
 u.username,
 m.message
from
 users u
inner join messages m on u.u_ID = m.author_id
order by
 m.m_ID;

答案 2 :(得分:0)

select m.m_ID, u.username, m.message 
from messages m inner join users u on u.u_ID = m.auhor_id