[英]How to get data referenced in another table in one MySQL query
I would to select some data from mysql. 我会从mysql中选择一些数据。 However, some of the data stored in the table I am querying from are in codes and to get the text description I need to reference that data to another table. 但是,存储在我要查询的表中的某些数据在代码中,并且为了获取文本描述,我需要将该数据引用到另一个表中。
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
How can I combine all three queries together to return id, first_name, last_name, address_name, customer_type_name in one query instead of querying them 3 times like this? 如何将所有三个查询组合在一起以在一个查询中返回id,first_name,last_name,address_name,customer_type_name,而不是像这样查询3次?
What you're looking for is a JOIN
. 您正在寻找的是JOIN
。
In a JOIN
, you specify two tables and how they are related to one another. 在JOIN
,您可以指定两个表以及它们之间的关系。 In a single SELECT
statement, you can have multiple JOIN
clauses. 在一个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
This query says that the table persons
and ref_address
should be linked, or "joined", by the related columns address_code
which are available in each table. 该查询说,表persons
和ref_address
应该由每个表中可用的相关列address_code
链接或“联接”。 Same goes with the tables persons
and ref_customer_type_code
being linked by the columns customer_type_code
. 同去同表persons
,并ref_customer_type_code
由列被链接customer_type_code
。
Please read the reference manual for join
. 请阅读join
的参考手册 。
In short, you need to define a relation between your tables (I use aliases just to make things a bit "cheaper" to write): 简而言之,您需要定义表之间的关系(我使用别名只是为了使事情写得更“便宜”):
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
Notice that when you use multiple tables in a query it may be useful to define aliases to avoid having to write again and again the full name of the table. 请注意,在查询中使用多个表时,定义别名可能会很有用,以避免不得不一次又一次地写入表的全名。 Also, it may be a good idea to explicitly specify each field's source table (by alias, if you are using it) 另外,最好明确指定每个字段的源表(如果使用别名,则通过别名)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.