2016-11-03 67 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