【问题标题】:How to get data referenced in another table in one MySQL query如何在一个 MySQL 查询中获取另一个表中引用的数据
【发布时间】:2014-09-22 02:44:13
【问题描述】:

我会从mysql中选择一些数据。但是,我查询的表中存储的一些数据是代码,为了获得文本描述,我需要将该数据引用到另一个表。

TABLE: persons

SELECT id, first_name, last_name, address_code, customer_type_code
FROM persons
WHERE id = 1001    

TABLE: ref_address 

SELECT address_name FROM ref_address
WHERE address_code = 123


TABLE: ref_customer_type_code   

SELECT customer_type_name FROM ref_customer_type_code
WHERE customer_type_code = 456

如何将所有三个查询组合在一起以在一个查询中返回 id、first_name、last_name、address_name、customer_type_name,而不是像这样查询 3 次?

【问题讨论】:

标签: php mysql sql


【解决方案1】:

Please read the reference manual for join.

简而言之,您需要定义表之间的关系(我使用别名只是为了让事情写起来更“便宜”):

select p.id, p.first_name, p.last_name, p.address_code, p.customer_type_code
     , ra.address_name
     , rctc.customer_type_name
from persons as p
     -- Join the persons table with the ref_address table, 
     -- using the address_code column of each table
     inner join ref_adress as ra 
                on p.address_code = ra.address_code
     -- Join the persons table with the ref_customer_type_code table
     -- using the customer_type_code column of each table
     inner join ref_customer_type_code as rctc 
                on p.customer_type_code = rctc.customer_type_code
where p.id = 1001

请注意,当您在查询中使用多个表时,定义别名可能很有用,以避免一次又一次地写入表的全名。此外,显式指定每个字段的源表可能是个好主意(如果您正在使用,则通过别名)

【讨论】:

    【解决方案2】:

    您要查找的是JOIN

    JOIN 中,您指定两个表以及它们如何相互关联。在单个SELECT 语句中,可以有多个JOIN 子句。

    SELECT
        p.id, p.first_name, p.last_name, p.address_code, p.customer_type_code,
        a.address_name,
        t.customer_type_name
    
    FROM
        persons p
    
        JOIN ref_address a
            ON p.address_code = a.address_code
    
        JOIN ref_customer_type_code t
            ON p.customer_type_code = t.customer_type_code
    
    WHERE
        p.id = 1001
    

    此查询表示表 personsref_address 应由每个表中可用的相关列 address_code 链接或“连接”。表personsref_customer_type_code 也是如此,它们由customer_type_code 列链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多