我有一个包含这些值的表:
id
parent_id
type
我想编写一个查询,如果满足这些条件,该查询将创建并存储在一个变量中:
例如 :
Id = 1, parent_id = 11, type = 1
Id = 2, parent_id = 1, type = 2
Id = 3, parent_id = 4, type = 2
Id = 4, parent_id = 7, type = 1
Id = 5, parent_id = 8, type = 2
Id = 6, parent_id = 9, type = 1
Id = 7, parent_id = 0, type = 3
Id = 8, parent_id = 0, type = 3
Id = 9, parent_id = 0, type = 3
因此,从这些数据中,只有 id 6 的变量包含 1,所有其他变量均为 0,因为它们不符合条件
换句话说,我想验证每个当前数据与任何其他数据的 parent_id 都不匹配。
换句话说,我不想有id
=parent_id
和有type
= 1。
如何使用上述条件执行 if 条件?我特别希望它在 if 条件中,因为 if 将在更大查询的选择中。
就像是
if ( id is in parent_id ( of all the
parent_id
fields in the database ), 1, 0 ) AS 条件
我希望我的问题很清楚!如果您有任何问题,请随时提出。
您的变量可以是一个单独的选择:
select t1.id pId, t1.type pType, (
select if(count(t2.id)=0 and pType=1, 1, 0 )
from tbl_name t2 where t2.parent_id=pId) cond
from tbl_name t1;
只要确保id
,parent_id
被索引,否则你将面临严重的性能损失。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句