简体   繁体   English

ORDER BY无法与GROUP BY一起使用

[英]ORDER BY not working as expected with GROUP BY

I have two tables, establishment and branch. 我有两个表,建立和分支。 Establishment is the parent table. 建立是父表。 When I select a list of branches, I want it to retrieve the establishment name if the branch title is blank. 当选择分支列表时,如果分支标题为空白,我希望它检索机构名称。 Also, I only want to show a branch once for each establishment. 另外,我只想为每个机构显示一次分支。 This is what I came up with: 这是我想出的:

SELECT 
  branch.id
  , branch.establishment_ID
  , IFNULL(branch.branch_title, establishment.name) AS branch_title 
FROM branch 
LEFT JOIN establishment ON branch.establishment_ID = establishment.id 
WHERE cityID = 2 
GROUP BY establishment_ID 
ORDER BY branch_title

However, the results do not appear to be in any particular order. 但是,结果似乎没有任何特定的顺序。 I want them to be in alphabetical order. 我希望它们按字母顺序排列。 I've read that MySQL 5.0.5 had problems with GROUP BY and ORDER BY in the same query, but I'm working with 5.5.9. 我已经读到MySQL 5.0.5在同一查询中存在GROUP BY和ORDER BY的问题,但是我正在使用5.5.9。 What can I do to fix this query? 我该如何解决此查询?

I would guess (knowing other SQL systems) that your ORDER BY is applying to branch.branch_title , rather than to your new alias. 我猜(知道其他SQL系统)您的ORDER BY正在应用于branch.branch_title ,而不是您的新别名。 Are you able to copy your IFNULL() expression into the ORDER BY ? 您能够将IFNULL()表达式复制到ORDER BY吗?

SELECT 
  branch.id
  , branch.establishment_ID
  , IFNULL(branch.branch_title, establishment.name) AS branch_title 
FROM branch 
LEFT JOIN establishment ON branch.establishment_ID = establishment.id 
WHERE cityID = 2 
GROUP BY establishment_ID 
ORDER BY IFNULL(branch.branch_title, establishment.name)

Otherwise, the NULL branch_title rows will always appear (before/after) the non- NULL ones, and will not be sorted in any way. 否则, NULL branch_title行将始终出现在非NULL行之前(之前/之后),并且不会以任何方式进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM