【问题标题】:same table as two and same column与两个相同的表和相同的列
【发布时间】:2014-05-29 10:08:29
【问题描述】:

我有两张桌子: 1-messages_system_data

    CREATE TABLE IF NOT EXISTS `messages_system_data` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `msgId` int(11) NOT NULL,
  `theSubject` varchar(250) NOT NULL,
  `sentMemId` int(11) NOT NULL,
  `receiveMemId` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) 

2 个成员

CREATE TABLE IF NOT EXISTS `members` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `theName` varchar(150) NOT NULL,
  PRIMARY KEY (`id`),
) 

我需要检索发送者消息名称和接收者消息名称。 messages_system_data 保留发送者的 ID 和接收者的 ID。我应该只使用一个 sql 命令。我是这样写的:

SELECT messages_system_data.theSubject, ?(here should be receiver ),?( sender name)  FROM  messages_system_data,members WHERE messages_system_data.sentMemId=members.id AND messages_system_data.receiveMemId=members.id LIMIT :limit, :offset

在这个 sql 中,有两个成员表加入,我怎样才能到达 theName 列的这个成员表?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您的问题似乎是您不习惯在同一查询中两次加入给定表。在我看来,如果您使用显式连接语法而不是逗号语法,则更容易准确了解这类事情(以及一般的连接)。

    SELECT
        messages_system_data.theSubject,
        sender.theName AS sender_name,
        recipient.theName AS recipient_name
    FROM
        messages_system_data
        JOIN members AS sender ON messages_system_data.sentMemId = sender.id
        JOIN members AS recipient ON messages_system_data.receiveMemId = recipient.id
    

    顺便说一句,为什么members.idBIGINTmessages_system_data.sentMemIdmessages_system_data.receiveMemIdINTs?它们应该是同一类型。

    【讨论】:

    • 感谢您的 sql 完美运行。我在公司工作。我不知道为什么类型不同
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多