2016-11-03 69 views
0

我有一個查詢,其結果就像$a=[1, 3, 5]查詢來獲取基於連接表列陣列上記錄

陣列我需要另一個查詢其返回從表1的記錄,所有的B值都在$a=[1,3, 5]所以導致了這個樣本table1.id=1, 2

我可以執行此查詢或我必須使用php代碼array_diff()來檢查b列和$ a之間的區別嗎?

**table1** 
id 
----------- 
1  ... 
2  ... 
3  ... 

**table 2** 
table1_id b 
------------ 
1   1 
1   3 
2   1 
3   1 
3   4 
4   1 
4   3 
4   5 
4   4 
+1

你的問題並不清楚..嘗試解釋更好..顯示真實的數據和實際預期的結果 – scaisEdge

+0

您可以在PHP中使用'implode()'並在MySQL中使用'IN()'條件。你也可以使用'JOIN'。 –

+0

謝謝你保羅,但我的問題是我可以解決單個sql查詢或我需要像implode()或array_diff()和PHP的功能呢? – user677900

回答

1

如果我理解正確的話:

SELECT * FROM table2 WHERE table2.b IN (SELECT id FROM table1 WHERE YourCondition) 

如果你想加入多個表,與例如ID匹配,使用:

Select * from table1 inner join table2 on table1.id=table2.table1_id 
+0

感謝里卡多,但條件是在table2上,我想如何比較每個記錄的b值與$ a? – user677900

+0

YourCondition,是你需要的table1的任何ID,如果你想從表1中的每一條記錄,只需把「where 1」 –

+1

對不起ricardo。我想我解釋我的問題不清楚。我想我的答案是這樣的帖子:http://stackoverflow.com/questions/26204792/select-1-record-from-first-table-if-condition-is-true-in-second-table- all-refea select table1.id from table1 join table2 on table1.id = table2.table1.id group by table1.id having sum(case when b not in $ a then 1 else 0 end)= 0 – user677900