在2列= 1列上连接两次mysql表

时间:2012-07-19 19:19:42

标签: mysql

我有一个包含消息的数据库。消息存储在一个表中,用户信息存储在另一个表中。在消息表中,有一个author_id列,表示来自用户表的作者的user_id,有所有消息列,并且有一个to_address表示来自用户表的“u_”+ user_id的串联。有没有我可以加入这两个表,以便它在author_id AND to_address中显示用户名而不是ID。

我试过

SELECT  username, ..., username
  FROM msgs
    INNER JOIN users
      ON user_id=author_id AND concat("u_",user_id)=to_address;

有明显的错误 我尝试过使用

之类的子查询
SELECT
  ( SELECT username 
      FROM users
        INNER JOIN msgs
          ON user_id=author_id
  ) AS "From",
  ( SELECT username
      FROM users
        INNER JOIN msgs
          ON CONCAT("u_",user_id)=to_address
  ) AS "To",
  ( SELECT timestamp(message_time) FROM msgs
  ) AS "Sent",
  ( SELECT message_subject FROM msgs
  ) AS "Subject",
  ( SELECT message_text AS "Message" FROM msgs
  ) AS "Message"

并获得“Subquery返回超过1行”。有什么方法可以成功地做到这一点吗?

4 个答案:

答案 0 :(得分:1)

听起来你想要这样的东西:

SELECT
    from_user.username AS "From",
    to_user.username AS "To",
    timestamp(msgs.message_time) AS "Sent",
    msgs.message_subject AS "Subject",
    msgs.message_text AS "Message"

FROM msgs

INNER JOIN users AS from_user
ON msgs.author_id = from_user.user_id

INNER JOIN users AS to_user
ON msgs.to_address = CONCAT("u_", to_user.user_id);

基本上,您将users表加入msgs表两次,为表的每个实例提供不同的名称和不同的连接条件。然后,您可以从users表的特定实例中选择一个特定列。

答案 1 :(得分:0)

我想你想做点什么

SELECT msgs.*,
       authors.whatever,
       addresses.to_address
  FROM msgs
  JOIN users AS authors ON msgs.author_id = authors.id
  JOIN users AS addresses ON msgs.address_id = addresses.id

我的查询可能不准确,但您可能会看到我在这里做的事情。

顺便说一句,我建议not abbreviating msgsusing singular table names

答案 2 :(得分:0)

您需要两个连接,因为您希望获得两个不同的用户:

select f.username, t.username
from msgs m
inner join users f on f.user_id = m.author_id
inner join users t on concat("u_", t.user_id) = m.to_address

答案 3 :(得分:0)

这将返回与" author_id"相关联的用户名。 " to_address",使用相关子查询,而不是使用JOIN。 (使用JOIN是常用的方法,但使用相关子查询的方法可以为您提供额外的灵活性。

SELECT (SELECT u.username 
          FROM users u 
            ON u.user_id = CONCAT("u_",u.user_id) = m.to_address
         ORDER BY u.username LIMIT 1
       ) AS to_username
     , (SELECT a.username 
          FROM users a 
            ON a.user_id = m.author_id
           ORDER BY a.username LIMIT 1
       ) AS author_username
     , m.*
  FROM msgs m

注意:这与INNER JOIN略有不同,因为当找不到to_address或author_id的匹配用户名时,这将从msg返回一行。)

注意:这假定user_id在users表中是唯一的。

注意:如果users表中的用户名列为NOT NULL,则可以模拟INNER JOIN,如果找不到author_id或to_address的匹配用户名,则不返回行

HAVING to_username IS NOT NULL
   AND author_username IS NOT NULL