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

Posted

技术标签:

【中文标题】从一个表中获取不同的行和*【英文标题】:Obtain distinct row and * from one table 【发布时间】:2015-03-13 22:40:28 【问题描述】:

我正在尝试获取与其他三列(品牌、型号和组)相关的三行汽车,我只想按型号获取一辆车。

这里是 mysql 表的图像:

你会看到三行具有相同的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):

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

【问题讨论】:

问题是除了你想要的模型ID之外还有哪些列?您可以使用“分组依据”子句将数据分组。如果您只想要 id,您可以执行“从汽车中选择不同的 model_id” 我们如何知道为 car_doors 选择什么值 - 两行说 5,一行说 3? 为什么这个问题同时标记了 MySQL 和 SQL Server?您实际使用的是哪个平台? i.stack.imgur.com/Dc7B7.png 【参考方案1】:

如果您仍想返回所有列,您可以创建子查询以仅返回每个模型一辆汽车,然后像以前一样编写查询:

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;

【讨论】:

【参考方案2】:
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

【讨论】:

【参考方案3】:

这有用吗?

    ;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

【讨论】:

以上是关于从一个表中获取不同的行和*的主要内容,如果未能解决你的问题,请参考以下文章

您可以对数据透视表中的行和/或列进行小计吗?

确定表中输入的行和列索引

Oracle 10g 从两个不同的行和列聚合成一行

使用jquery动态添加和删除表中的行和列

UNION JOIN 连接表

从 SQL 数据库中选择特定的行和列