簡體   English   中英

從子查詢返回多行

[英]Return multiple rows from subquery

基本上我有兩個表。 1和2。我需要table2表中的field2列返回多行。 我嘗試了以下聯接(簡化了列),但不幸的是,它僅返回一個結果。

SELECT table1.field1, table1.field2, table1.field3, sub_q.field4
FROM table1
JOIN (
    SELECT t2.field4, t2.filter1, t2.filter2 FROM table2 t2
) sub_q ON (sub_q.filter1 = table1.id AND sub_q.filter2 = 1) 
##Should return multiple rows
##but returns only one!
WHERE table1.id = ..;

編輯:

我在這里創建了一個模式: http : //sqlfiddle.com/#!9/1c5737 ,其中select查詢為

SELECT t1.field1, t1.field2, t1.field3, t2.field1
FROM table1 t1
JOIN table2 t2 ON t2.filter1 = t1.id AND t2.filter2 = 1
WHERE t1.id = 1;

只是發現它在那里起作用,所以我羞愧地回來接受答案並檢查我在查詢中弄錯了什么地方(可能是字段之一)

為什么在聯接中使用子查詢? 它應該這樣寫:

SELECT table1.field1, table1.field2, table1.field3, t2.field1
FROM table1 t1
JOIN table2 t2 ON t2.filter1 = table1.id AND t2.filter2 = 1 

同樣,您可能需要LEFT JOIN (或INNER JOIN )而不是JOIN ,但是如果沒有更多關於您要實現的目標的詳細信息,就無法確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM