【问题标题】:Complex MySQL query with multiple select statements具有多个选择语句的复杂 MySQL 查询
【发布时间】:2013-03-01 15:18:40
【问题描述】:

我在 Mysql 中有三个链接在一起的表:

个人资料(ID、姓名、资料..)

联系人(ID、ProfileID、desc、Ord)

地址(ID、ProfileID、desc、Ord)

现在我需要从个人资料表中选择所有个人资料,其中 “desc” 字段来自联系人和地址,其中 Ord = 1。(这是一个搜索功能,我将在表格中显示姓名,主要联系人客户的信息和主要地址。

我目前可以使用三个单独的 SQL 请求来做到这一点:

SELECT Name, ID FROM Profile WHERE name=”bla”

然后在一个 foreach 循环中,我将运行另外两个请求:

SELECT ProfileID, desc FROM Contact WHERE ProfileID=MyProfileID AND Ord=1
SELECT ProfileID, desc FROM Address WHERE ProfileID=MyProfileID AND Ord=1

我知道您可以在一个查询中执行多个 SELECT,有没有办法可以将所有三个 SELECT 分组到一个查询中?

【问题讨论】:

    标签: mysql select multi-table


    【解决方案1】:

    您应该能够JOINprofile.id 上的表和其他表中的profileid

    如果您确定所有三个表中都存在profileid,那么您可以使用INNER JOININNER JOIN 返回所有表中的匹配行:

    select p.id,
      p.name,
      c.desc ContactDesc,
      a.desc AddressDesc
    from profile p
    inner join contact c
      on p.id = c.profileid
    inner join address a
      on p.id = a.profileid
    where p.name = 'bla'
      and c.ord = 1
      and a.ord = 1
    

    如果您不确定是否有匹配的行,那么您可以使用LEFT JOIN

    select p.id,
      p.name,
      c.desc ContactDesc,
      a.desc AddressDesc
    from profile p
    left join contact c
      on p.id = c.profileid
      and c.ord = 1
    left join address a
      on p.id = a.profileid
      and a.ord = 1
    where p.name = 'bla'
    

    如果您在学习JOIN 语法方面需要帮助,这里有一个很棒的visual explanation of joins

    【讨论】:

    • 非常感谢! 1 用于解释,2 用于链接,您的信息和 JW 信息都有助于我更好地理解 SQL...(我喜欢理解和学习答案,而不仅仅是复制粘贴!!!!
    【解决方案2】:

    Profile 表中的ID 在表上至少有一个匹配项:ContactAddress 时,下面的此查询仅选择列。如果其中一个或两个都可为空,请使用LEFT JOIN 而不是INNER JOIN,因为LEFT JOIN 显示左侧 侧表中的所有记录,无论它是否有是否匹配其他表。

    SELECT  a.*, 
            b.desc as BDESC,
            c.desc as CDESC
    FROM    Profile a
            INNER JOIN Contact b
                ON a.ID = b.ProfileID
            INNER JOIN Address c
                ON a.ID = c.ProfileID
    WHERE   b.ORD = 1 AND
            c.ORD = 1 AND
            a.Name = 'nameHERE'
    

    LEFT JOIN 版本:

    SELECT  a.*, 
            b.desc as BDESC,
            c.desc as CDESC
    FROM    Profile a
            INNER JOIN Contact b
                ON a.ID = b.ProfileID AND b.ORD = 1
            INNER JOIN Address c
                ON a.ID = c.ProfileID AND c.ORD = 1
    WHERE   a.Name = 'nameHERE'
    

    如需进一步了解联接,请访问以下链接:

    【讨论】:

    • HI JW,你可以看看给bluefeet留下的评论,谢谢你也适用于你!!!
    【解决方案3】:

    我已根据您的要求创建了working demo

    下面的查询将从数据库中检索所有匹配的记录。它检索个人资料 ID、姓名资料和联系表的描述

    select p.id,p.name,p.stauff,c.descr,a.descr from profile as p
     inner join contact as c on c.profileid=p.id
     inner join address as a on a.profileid=p.id
     where p.name="bla" and c.ord=1 and a.ord=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2013-08-29
      相关资源
      最近更新 更多