gpt4 book ai didi

mysql - 如何为一对多映射记录编写查询

转载 作者:行者123 更新时间:2023-11-29 06:16:04 26 4
gpt4 key购买 nike

我有这三张表。

  • channel (id、id_account、种类、日期时间、状态、id_target)
  • channel_contacts(id、id_channel、id_contact、存档)
  • channel_events(id、id_channel_contacts、代码、详细信息、日期时间)

channel_contacts 与 channel 的关系

PRIMARY KEY (`id`),
UNIQUE INDEX `CONTRAINT` (`id_channel`, `id_contact`),
INDEX `idx_channel_contact_archived` (`archived`),
INDEX `channel_contacts_ibfk_2` (`id_contact`),
CONSTRAINT `channel_contacts_ibfk_1` FOREIGN KEY (`id_channel`) REFERENCES `channels` (`id`) ON DELETE CASCADE,
CONSTRAINT `channel_contacts_ibfk_2` FOREIGN KEY (`id_contact`) REFERENCES `contact` (`id_contact`) ON DELETE SET NULL

channel_events 与 channel_contacts 的关系

PRIMARY KEY (`id`),
INDEX `id_channel_contacts` (`id_channel_contacts`),
CONSTRAINT `channel_events_ibfk_1` FOREIGN KEY (`id_channel_contacts`) REFERENCES `channel_contacts` (`id`) ON DELETE CASCADE

可以看出它们是相关的。

我想要 channels_events 表中属于 channels 表中 id_account 123 的所有事件。

我写了下面的查询,它给了我下面的问题

Unknown column 'channel_contacts.id_channel' in 'on clause'

SELECT channels.id, channels.kind, channels.publish_date,
channel_contacts.id_channel, channel_contacts.id_contact,
channel_contacts.archived, channel_events.id,
channel_events.id_channel_contacts, channel_events.code,
channel_events.details, channel_events.occation
FROM channel_events
JOIN channels
ON channels.id = channel_contacts.id_channel
JOIN channel_contacts
ON channel_contacts.id_contact = channel_events.id_channel_contacts
where channels.id_account = 123;

最佳答案

我认为这是一个打字错误,您已将与 channel 连接表放置在 channel 联系人之前,因此尚未识别 channels_contanct。试试这个:

SELECT channels.id, channels.kind, channels.publish_date, channel_contacts.id_channel, channel_contacts.id_contact, channel_contacts.archived, channel_events.id, channel_events.id_channel_contacts, channel_events.code, channel_events.details, channel_events.occation
FROM channel_events
JOIN channel_contacts ON channel_contacts.id= channel_events.id_channel_contacts
JOIN channels ON channels.id = channel_contacts.id_channel
where channels.id_account = 123;

关于mysql - 如何为一对多映射记录编写查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com