伙计们,我很难想出一个能为我提供以下输出的SQL:
ID|CITY_SLUG|BAIRRO|NEIGHBORHOOD_BAIRRO|CIDADE|UF|STATE_SLUG
4444|4444|Porto Alegre do Norte
5671|5671|Porto Alegre do Piauí
7994|7994|Porto Alegre
9919|9919|Porto Alegre do Tocantins
12538|12538|Linha Porto Alegre
12538|12538|Centro|63310|Linha Porto Alegre|RS|rs
7994|7994|Aberta dos Morros|13460|Porto Alegre|RS|rs
4444|4444|Centro|38981|Porto Alegre do Norte|MT|mt
5671|5671|Centro|39387|Porto Alegre do Piauí|PI|pi
9919|9919|Setor Central|32994|Porto Alegre do Tocantins|TO|to
4444|4444|Centro|38981|Porto Alegre do Norte|MT|mt
5671|5671|Centro|39387|Porto Alegre do Piauí|PI|pi
7994|7994|Aberta dos Morros|13460|Porto Alegre|RS|rs
这个想法是首先列出城市,然后列出匹配城市名称的邻域,这是我的sql:
Select
CITY.ID,
CITY.SLUG as CITY_SLUG,
NEIGHBORHOOD.NAME as BAIRRO,
NEIGHBORHOOD.SLUG AS NEIGHBORHOOD_BAIRRO,
CITY.NAME as CIDADE,
STATE.ABB AS UF,
STATE.SLUG AS STATE_SLUG
from CITY
LEFT OUTER join STATE on CITY.ID_STATE=STATE.ID
LEFT OUTER join NEIGHBORHOOD on NEIGHBORHOOD.ID_CITY = CITY.ID
WHERE (CITY.NAME LIKE '%PORTO ALE%' )
答案 0 :(得分:0)
正如@Barmar所提到的,首先获取具有匹配的城市名称的行,然后创建一个UNION,其行包含具有匹配城市名称的邻域。添加相关逻辑以忽略具有NULL值的列:
Select
CITY.ID,
CITY.SLUG as CITY_SLUG,
NEIGHBORHOOD.NAME as BAIRRO,
NULL,
NULL,
NULL,
NULL
from CITY
LEFT OUTER join STATE on CITY.ID_STATE=STATE.ID
LEFT OUTER join NEIGHBORHOOD on NEIGHBORHOOD.ID_CITY = CITY.ID
WHERE (CITY.NAME LIKE '%PORTO ALE%' )
UNION
Select
CITY.ID,
CITY.SLUG as CITY_SLUG,
NEIGHBORHOOD.NAME as BAIRRO,
NEIGHBORHOOD.SLUG AS NEIGHBORHOOD_BAIRRO,
CITY.NAME as CIDADE,
STATE.ABB AS UF,
STATE.SLUG AS STATE_SLUG
from CITY
LEFT OUTER join STATE on CITY.ID_STATE=STATE.ID
LEFT OUTER join NEIGHBORHOOD on NEIGHBORHOOD.ID_CITY = CITY.ID
WHERE (CITY.NAME LIKE '%PORTO ALE%' )