我有两个表,建立和分支。建立是父表。当我选择分支列表时,如果分支标题为空,我希望它检索企业名称。另外,我只想为每个机构展示一次分支。这就是我想出的:
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。我该怎么做才能解决这个问题?
答案 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
行,并且不会以任何方式排序。