[英]mysql select multiple columns of one row from another table
I usually google my questions, since they are not unique only to me. 我通常会用谷歌搜索我的问题,因为它们不仅是我独有的。 However, this time I can't find answer (probably not using right keywords).
但是,这次我找不到答案(可能没有使用正确的关键字)。
Problem description: 问题描述:
I have two tables. 我有两张桌子。
First table - defenition_list holds unique ID and Name 第一个表-defenition_list拥有唯一的ID和名称
ID | NAME
-----------
1 | BMW
2 | AUDI
3 | VW
4 | MAZDA
Second Table - used_id holds ID from first table 第二个表-used_id保存第一个表的ID
ID | def_uid1 | def_uid2 | def_uid3
------------------------------------
1 | 2 | 3 | 2
2 | 4 | 2 | 1
So usually If I need to return value of just one column, I would make select like: 因此通常,如果我只需要返回一列的值,则可以选择:
SELECT d.NAME, u.def_uid1 FROM defenition_list d, used_id u WHERE d.ID=u.def_uid1
But how to write the query to get names of def_uid2 and def_uid3 at same time? 但是如何编写查询以同时获取def_uid2和def_uid3的名称? So result would look like:
所以结果看起来像:
ID | def_uid1 | def_uid2 | def_uid3 |
--------------------------------------
1 | AUDI | VW | AUDI |
2 | MAZDA | AUDI | BMW |
You'd have to join your names table 3 times: 您必须加入名称表3次:
SELECT used_id.ID, d1.name, d2.name, d3.name
FROM used_id
LEFT JOIN definition_list AS d1 ON used_id.def_uid1 = d1.id
LEFT JOIN definition_list AS d2 ON ...
LEFT JOIN definition_list AS d3 ON ...
You have two options. 您有两个选择。 One option is to join your table several times, once for each column you need to grab, or you can write subqueries inside your select clause for each column, like this:
一种选择是多次联接您的表,一次需要为每个列抓取一次,也可以在select子句中为每列编写子查询,如下所示:
SELECT
u.id,
(SELECT name FROM definition_list WHERE id = u.def_uid1) AS def_uid1,
(SELECT name FROM definition_list WHERE id = u.def_uid2) AS def_uid2,
(SELECT name FROM definition_list WHERE id = u.def_uid3) AS def_uid3
FROM used_id u;
Here is an SQL Fiddle example, using both options that I mentioned. 这是一个SQL Fiddle示例,使用了我提到的两个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.