开发者

SQL - Regroup by subfield

开发者 https://www.devze.com 2023-03-09 21:30 出处:网络
I\'ve got a problem with my SQL. I have a table (named \"Regions\") looking like this : What I want to do is sorting this table wit开发者_JS百科h the sub_region \"next\" to the region. In this exem

I've got a problem with my SQL. I have a table (named "Regions") looking like this :

SQL - Regroup by subfield

What I want to do is sorting this table wit开发者_JS百科h the sub_region "next" to the region. In this exemple, Québec (9) and Ontario (10) are sub region of Canada (7) so I want to get them right after Canada. I don't know if it's stupid or my SQL is too rusty but I don't find a way to do that.... By the way, the website that will use this DB is with CakePHP, if that can be of any help!(Behavior or other built-in module, I don't know).


select s.id, s.name, r.*
from Regions r
left join Regions s
on s.id = r.sub_region
order by(coalesce(s.id, r.id), r.id)

edit: I modified the joined query, I haven't tried it, but would you give that a shot, I think that syntax should work for mysql

0

精彩评论

暂无评论...
验证码 换一张
取 消