我想做的是从数据库中查询所有唯一的区名称,并在每个区名称上获取其对应的MIN
和MAX
ID
。
这是我现在所拥有的:
SELECT DISTINCT DISTRICTNAME,
(SELECT MIN(`ID`)
FROM [DATABASE_NAME]
WHERE DISTRICTNAME = DISTRICTNAME) AS 'MIN',
(SELECT MAX(`ID`)
FROM [DATABASE_NAME]
WHERE DISTRICTNAME = DISTRICTNAME) AS 'MAX'
FROM [DATABASE_NAME]
WHERE [CONDITION]
ORDER BY DISTRICTNAME;
问题:
MIN
和MAX
列显示相同的值。我不太确定内部查询的WHERE
子句。我认为这就是问题所在。救命?
最佳答案
使用GROUP BY
子句尝试此查询
SELECT DISTRICTNAME, MIN(`ID`) AS 'MIN', MAX(`ID`) AS 'MAX'
FROM [DATABASE_NAME]
WHERE [CONDITION]
GROUP BY DISTRICTNAME
ORDER BY DISTRICTNAME;;
关于mysql - 在内部查询中的外部查询中使用结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30297985/