我有两个表,establishment 和 branch。建立是父表。当我选择一个分支列表时,如果分支标题为空,我希望它检索机构名称。另外,我只想为每个机构显示一次分支机构。这是我想出的:
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。我该怎么做才能修复此查询?
最佳答案
我猜(了解其他 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
行,并且不会以任何方式排序。
关于mysql - ORDER BY 无法按预期使用 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7872513/