【问题标题】:Joining 3 tables with mySQL with 1 query通过 1 个查询将 3 个表与 mySQL 连接起来
【发布时间】:2016-01-26 21:51:44
【问题描述】:

已经在不同的情况下提出并回答了这个问题,但我所看到的一切都不能完全解决我的问题。

问题:我需要同时从 3 个表中提取数据以比较和检索信息。所有 3 个表都包含一个“电子邮件”列。现在,来自 table1 的用户的电子邮件可能与 table2 和 table3 中的同一用户的电子邮件匹配,具体取决于用户的状态。或者来自 table1 的电子邮件将仅匹配 table2 或 table3 中的电子邮件,这取决于用户的状态。例如,用户可能具有红色状态(用户将显示在 table2 中)、蓝色状态(用户将显示在 table3 中)或两者兼有,红色和蓝色(用户将同时显示在 table2 和 table3 中)。

需要什么:需要将来自 table1 的电子邮件与 table2 和 table3 中的电子邮件进行比较,并返回给定用户的区域值,该值记录在 table2 和 table3 中,但不在 table1 中。我知道。令人愉快的数据架构!无论哪种方式,我都能够非常成功地将JOIN table1 转换为 table2,但我不知道如何用 table3 拍JOIN

这是对 2 个表的查询:

SELECT * FROM table1
INNER JOIN table2
ON table2.email = table1.email
WHERE month = 'numberHere' ORDER BY submitdate DESC

当我简单地添加另一个 INNER JOIN 时,我的代码不会按说中断,但它也不会给我任何要显示的行。因此,尽管网络上有许多工作示例,但下面的代码不起作用:

SELECT * FROM table1
INNER JOIN table2
ON table2.email = table1.email
INNER JOIN table3
ON table3.email = table2.email
WHERE month = 'numberHere' ORDER BY submitdate DESC

【问题讨论】:

  • 您需要发布所有 3 个表格的表格结构

标签: php mysql join


【解决方案1】:

要在任何情况下匹配来自table1 的行并且仅匹配其他表的行,您必须使用LEFT JOIN,将table2table3table1 连接起来(而不是table2 table1table3tabel2):

SELECT * FROM table1
LEFT JOIN table2
ON table2.email = table1.email
LEFT JOIN table3
ON table3.email = table1.email

通过这种方式,即使在其他表中没有匹配项,您也可以从 table1 中选择值。

查看更多关于 SQL 连接的信息:Different SQL Joins

【讨论】:

  • 我回去学习 SQL。 ;p 非常感谢。完美运行。
【解决方案2】:

您需要使用LEFT JOIN,这样即使其中一个表中没有匹配的行,连接也会成功。

SELECT * FROM table1
LEFT JOIN table2
    ON table2.email = table1.email
LEFT JOIN table3
    ON table3.email = table2.email
WHERE month = 'numberHere'
    AND (table2.email IS NOT NULL OR table3.email IS NOT NULL)
ORDER BY submitdate DESC

附加条件过滤掉任何一个表中都不匹配的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2020-11-04
    相关资源
    最近更新 更多