根据条件从 mysql 查询中获取 parent id
get parent id from mysql query based on condition
我有两个 table,一个是 parent_table,一个是 child_table。
我需要得到的是来自 parent_table 的 id 当状态等于 0 当 child_table 状态不等于 0 且仅当它不等于 0
例如 tables 是这样的:
parent_table
id , status
--------------------
1 , 0
2 , 0
child_table
id , parent_id, status
------------------------
1 , 2 , 2
2 , 2 , 1
3 , 2 , 1
我需要得到的是 parent table 的 id 并且只有当 child table 的状态不为 0
这是我尝试过的:
SELECT a.id FROM `parent_table` a inner join child_table b where b.status !=0 and a.status = 0 and a.id = b.parent_id
我需要的结果是:id 2 来自 parent_table
感谢帮助
您可以加入两个 tables,按 parent id 聚合,并使用 having
子句过滤掉任何 child 的 parents状态 0
:
select p.id
from parent_table p
inner join child_table c on c.parent_id = p.id
group by p.id
having max(c.status = 0) = 0
实际上,您可以直接从 child table:
得到相同的结果
select parent_id
from child_table
group by parent_id
having max(status = 0) = 0
我有两个 table,一个是 parent_table,一个是 child_table。
我需要得到的是来自 parent_table 的 id 当状态等于 0 当 child_table 状态不等于 0 且仅当它不等于 0
例如 tables 是这样的:
parent_table
id , status
--------------------
1 , 0
2 , 0
child_table
id , parent_id, status
------------------------
1 , 2 , 2
2 , 2 , 1
3 , 2 , 1
我需要得到的是 parent table 的 id 并且只有当 child table 的状态不为 0
这是我尝试过的:
SELECT a.id FROM `parent_table` a inner join child_table b where b.status !=0 and a.status = 0 and a.id = b.parent_id
我需要的结果是:id 2 来自 parent_table
感谢帮助
您可以加入两个 tables,按 parent id 聚合,并使用 having
子句过滤掉任何 child 的 parents状态 0
:
select p.id
from parent_table p
inner join child_table c on c.parent_id = p.id
group by p.id
having max(c.status = 0) = 0
实际上,您可以直接从 child table:
得到相同的结果select parent_id
from child_table
group by parent_id
having max(status = 0) = 0