如何在一个MySQL查询中获取另一个表中引用的数据


How to get data referenced in another table in one MySQL query

我想从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,而不是像这样查询三次?

请阅读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

请注意,当您在一个查询中使用多个表时,定义别名可能会很有用,以避免不得不反复写入表的全名。此外,显式指定每个字段的源表(如果您正在使用它,请使用别名)

可能是个好主意

您要找的是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链接也是如此。