两行之间的连接依赖于其他行,使用PHP和MySQL


Join between two rows depend on other row, using PHP and MySQL

对于每两行,我都有相同的"id"/num,并且我需要在2行中获得所有状态为0的num。

例如,在我的表格中,结果将是:

num: 2,3

因为对于num 2,类型a的状态为0,类型b的状态也为0。但是num 1在类型b中有1,所以它不是很好。

我如何做到这一点与SQL查询或JSON数据或数组在PHP?我的表是:

id | num | type  |state 
1  | 1   | a     | 0 
2  | 1   | b     | 1
3  | 2   | a     | 0
4  | 2   | b     | 0
5  | 3   | a     | 0
6  | 3   | b     | 0

你可以试试:

SELECT
  num
FROM myTable
GROUP BY num
HAVING sum(state) = 0

不包含相关子查询的自连接:

select t1.num
from tablexxx t1
join tablexxx t2
on t2.num=t1.num
and t2.state=0 and t1.state=0

num上添加索引