我想做的是从数据库中查询所有唯一的区名称,并在每个区名称上获取其对应的MINMAX 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;


问题:MINMAX列显示相同的值。我不太确定内部查询的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/

10-09 20:12