我在mysql中写一个查询,我对递归查询并不熟悉。 由于我提出的条件看起来不太好,因此我应该如何以及如何对以下查询进行优化,因此必须有一种更简单的方法。
select
b.entity_id
from
entity_hierarchies a,
entity_hierarchies b
where
a.entity_id = 25
and a.entity_type = 'user'
and b.entity_type = 'idea'
and a.Geography_Geography =
case
when
a.Geography_Geography is null
then
a.Geography_Geography
else
b.Geography_Geography
end
and COALESCE(a.Geography_Country, '') =
case
when
a.Geography_Country is null
then
COALESCE(a.Geography_Country, '')
else
b.Geography_Country
end
and COALESCE(a.Geography_DistrictOrCounty, '') =
case
when
a.Geography_DistrictOrCounty is null
then
COALESCE(a.Geography_DistrictOrCounty, '')
else
b.Geography_DistrictOrCounty
end
and COALESCE(a.Geography_State, '') =
case
when
a.Geography_State is null
then
COALESCE(a.Geography_State, '')
else
b.Geography_State
end
and COALESCE(a.Geography_City, '') =
case
when
a.Geography_City is null
then
COALESCE(a.Geography_City, '')
else
b.Geography_City
end
答案 0 :(得分:2)
我注意到您可以用更简单的形式重写其中一些语句。
例如:
and a.Geography_Geography =
case
when
a.Geography_Geography is null
then
a.Geography_Geography
else
b.Geography_Geography
end
可以简单地变成:
AND ( a.Geography_Geography is null or a.Geography_Geography = b.Geography_Geography )
select
b.entity_id
from
entity_hierarchies a,
entity_hierarchies b
where
a.entity_id = 25
and a.entity_type = 'user'
and b.entity_type = 'idea'
AND ( a.Geography_Geography is null OR a.Geography_Geography = b.Geography_Geography )
AND ( a.Geography_Country is null OR a.Geography_Geography = b.Geography_Country )
AND ( a.Geography_DistrictOrCounty is null OR a.Geography_DistrictOrCounty = b.Geography_DistrictOrCounty )
AND ( a.Geography_State is null OR a.Geography_State = b.Geography_State )
AND ( a.Geography_City is null OR a.Geography_City = b.Geography_City );