从一个表中获取不同的行和*

时间:2015-01-15 14:00:57

标签: mysql sql-server select

我试图获得一辆与其他三列(品牌,型号和组别)有三排关系的汽车,我只希望按型号购买一辆汽车。

这是MySQL表的图像: enter image description here

您将看到三行具有相同的model_id(model_id是外键另一个表,另一个表称为模型)

我获取这些汽车的SQL查询是:

SELECT *
FROM gm_cars AS cars
INNER JOIN gm_cars_makes AS makes
   ON (cars.make_id = makes.make_id)
INNER JOIN gm_cars_models AS models
   ON (cars.model_id = models.model_id)
INNER JOIN gm_cars_groups AS groups
   ON (cars.group_id = groups.group_id) AND
       makes.make_visible = 1
ORDER BY cars.model_id;

但是我想为一个模型获得一行,这里有一个例子(我使用过Photoshop): enter image description here

有些人喜欢:SELECT *, DISTINCT(model_id) FROM cars

3 个答案:

答案 0 :(得分:0)

如果您仍想返回所有列,则可以创建子查询,以便每个模型只返回一个Car,然后像以前一样写入查询:

SELECT * FROM gm_cars AS cars 
INNER JOIN (SELECT model_id, MAX(car_Id) AS car_Id FROM gm_cars GROUP BY model_id) AS grp_cars ON grp_cars.car_Id = cars.car_Id
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id) 
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id) 
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id) AND makes.make_visible = 1 ORDER BY cars.model_id;

您还可以在主查询中添加GROUP BY,并将聚合函数添加到所有其他列。但它可以使用相同的型号从不同的汽车返回列:

SELECT cars.model_id,
    MAX(car_passengers),
    MAX(car_suitcases),
    ....
FROM gm_cars AS cars 
INNER JOIN (SELECT model_id, MAX(car_Id) AS car_Id FROM gm_cars GROUP BY model_id) AS grp_cars ON grp_cars.car_Id = cars.car_Id
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id) 
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id) 
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id) AND makes.make_visible = 1 
GROUP BY cars.model_id
ORDER BY cars.model_id;

答案 1 :(得分:0)

SELECT * 
FROM gm_cars AS cars 
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id) 
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id) 
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id) 
AND makes.make_visible = 1 
group by (model_id)
ORDER BY cars.model_id

答案 2 :(得分:0)

这有用吗?

    ;with cte 
    AS
    (
        Select *,row_number() OVER(partition by model_id order by car id) rn from gm_cars 
    )

    select * from cte where rn=1