在内部查询中使用外部查询中的结果

时间:2015-05-18 08:06:35

标签: mysql sql subquery

我要做的是从数据库中查询所有唯一的地区名称,并在每个地区名称上获取相应的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子句。我认为这就是问题所在。

帮助?

1 个答案:

答案 0 :(得分:3)

使用GROUP BY子句

尝试此查询
SELECT DISTRICTNAME, MIN(`ID`) AS 'MIN', MAX(`ID`) AS 'MAX'
FROM [DATABASE_NAME]
WHERE [CONDITION]
GROUP BY DISTRICTNAME
ORDER BY DISTRICTNAME;;