MySQL在表2上选择多行,其中两个不同于表1中的Id,导致一行作为两个不同的字段

时间:2015-11-25 14:27:14

标签: mysql sql

只有一个MySQL查询可以将所需的结果(下面)返回到一行吗?

表1中id = 1

表1

|------|----------|----------|
| id   | refIdOne | refIdTwo |
|------|----------|-----------
| 1    | 1        | 2        |
|------|----------|-----------

列“refIdOne”& “refIdTwo”参见表2“id”栏

表2

|------|------------------|
| id   | text             |
|------|------------------|
| 1    | cheese           |
| 2    | made with milk   |
|------|------------------|

在ONE ROW中返回所需的结果,其中包含名为“subject”和“description”的自定义AS列:

|----------|-----------------|
| subject  | description     |
|----------|-----------------|
| cheese   | made with milk  |

?非常感谢您的帮助

*编辑:答案为*

select t21.text as subject, t22.text as description
from Table1 as t1
join Table2 as t21 on t1.refidone = t21.id
join Table2 as t22 on t1.refidtwo = t22.id
where t1.id = 1

3 个答案:

答案 0 :(得分:0)

Table2必须连接两次到Table1。

select t21.text as subject, t22.text as description
from table1 t1
join table2 t21 on t1.refidone = t21.id
join table2 t22 on t1.refidtwo = t22.id

答案 1 :(得分:0)

您需要执行Self join。使用Table2IDTable1加入refIdOneTable1两次。refIdTwo

select t2.text as subject, t3.text as description 
from Table1  t1 
Left join Table2 t2 on t1.refIdOne = t2.id
Left join Table2 t3 on t1.refIdTwo = t2.id

答案 2 :(得分:0)

没有加入

SELECT
(SELECT text FROM Table2 WHERE id = (SELECT refIdOne FROM Table1 WHERE id = 1) ) AS name,
(SELECT text FROM Table2 WHERE id = (SELECT refIdTwo FROM Table1 WHERE id = 1) ) AS description