只有一个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
答案 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
。使用Table2
。ID
和Table1
加入refIdOne
。Table1
两次。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