[英]MYSQL Retrieving data from a table where id is not present in a column of two differents tables
[英]MySQL select multiple row on table 2 with two differents Id from table 1 result in one row as two differents fields
是否有可能僅在一個 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
表 2 必須兩次連接到表 1。
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
您需要執行Self join
。 加入表Table2
。 使用Table1
ID
兩次。 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
沒有連接
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.