0

我有一个包含消息的数据库。消息存储在一个表中,用户信息存储在另一个表中。在message表中,有一个author_id列,代表user表中作者的user_id,有所有message列,还有一个to_address,代表user表中“u_”+user_id的串联。有什么我可以加入这两个表的,以便它在 author_id 和 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"

并得到“子查询返回超过 1 行”。有什么方法可以让我成功地做到这一点?

4

4 回答 4

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

于 2012-07-19T19:24:11.020 回答
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

我的查询可能不精确,但您可能可以看到我在这里做什么。

顺便说一句,我建议不要缩写 msgs使用单数表名

于 2012-07-19T19:26:38.993 回答
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
于 2012-07-19T19:28:51.753 回答
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 表中是唯一的。

注意:如果用户表中的用户名列不为 NULL,那么您可以模拟 INNER JOIN,并且如果未找到 author_id 或 to_address 的匹配用户名,则通过添加

HAVING to_username IS NOT NULL
   AND author_username IS NOT NULL
于 2012-07-19T19:40:04.220 回答