ORDER BY与GROUP BY无法正常工作

时间:2011-10-24 07:36:49

标签: mysql sql group-by sql-order-by left-join

我有两个表,建立和分支。建立是父表。当我选择分支列表时,如果分支标题为空,我希望它检索企业名称。另外,我只想为每个机构展示一次分支。这就是我想出的:

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

但是,结果似乎没有任何特定的顺序。我希望它们按字母顺序排列。我已经读过MySQL 5.0.5在同一个查询中遇到GROUP BY和ORDER BY的问题,但我正在使用5.5.9。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

我猜(知道其他SQL系统)你的ORDER BY正在申请branch.branch_title,而不是你的新别名。您是否可以将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)

否则,NULL branch_title行将始终显示(之前/之后)非NULL行,并且不会以任何方式排序。