简体   繁体   English

Mysql 区分一列但不是每一列

[英]Mysql Distinct one column but not every column

I have a table (a list of cars, years and models) and I am trying to show a list of just the years, but the list of years that manufacture has made a car could be huge.我有一张表格(汽车、年份和型号的列表),我试图仅显示年份列表,但是制造商制造汽车的年份列表可能很大。 Meaning when I query "Volvo" Im returning a list of all years Volvo has made a car, Using:意思是当我查询“沃尔沃”时,我会返回沃尔沃制造汽车的所有年份的列表,使用:

"SELECT id, year FROM `models_auto` WHERE `make`=? ORDER BY `year` DESC;"

However, Volvo may have made 50 cars that year and the return is all 50 duplicate years.然而,沃尔沃那一年可能已经生产了 50 辆汽车,而回报是所有 50 年的重复年份。 I want to return just unique list of years, not duplicates.我只想返回唯一的年份列表,而不是重复的。 I looked at DISTINCT but using:我看着 DISTINCT 但使用:

"SELECT DISTINCT id, year FROM `models_auto` WHERE `make`=? ORDER BY `year` DESC;"

Still returns everything because ID is unique.仍然返回所有内容,因为 ID 是唯一的。 How can I only DISTINCT year?我怎么能只有不同的年份?

Thank you.谢谢你。

If you want only the years then you can use use GROUP BY .如果您只想要年份,那么您可以使用GROUP BY

SELECT `year`
FROM `models_auto`
WHERE `make`=? 
GROUP BY `year`
ORDER BY `year` DESC;"

Or using DISTINCT :或使用DISTINCT

SELECT DISTINCT `year`
FROM `models_auto`
WHERE `make`=? 
ORDER BY `year` DESC;"

One option is to return the years as a comma delimited list, using group_concat() :一种选择是使用group_concat()将年份作为逗号分隔的列表返回:

select make, group_concat(distinct year order by year)
from models_auto
group by make;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM