【发布时间】:2012-07-06 13:36:36
【问题描述】:
select model from (
select price, model from pc where price = (select max(price) from pc)
union
select price, model from laptop where price = (select max(price) from laptop)
union
select price, model from printer where price = (select max(price) from printer)
) t1 where price = (select max(price) from (
select price, model from pc where price = (select max(price) from pc)
union
select price, model from laptop where price = (select max(price) from laptop)
union
select price, model from printer where price = (select max(price) from printer)
) t2 )
我对 SQL 很陌生,所以我的问题很简单,但我想理清一点。我对这个查询不能简化为这样的事情是对的吗?
select model from (
select price, model from pc where price = (select max(price) from pc)
union
select price, model from laptop where price = (select max(price) from laptop)
union
select price, model from printer where price = (select max(price) from printer)
) t1 where price = (select max(price) from t1)
如果不能,我们运行两个相同的子查询是不是一件坏事?
【问题讨论】:
-
仅通过查看查询很难理解表结构以及您要实现什么。?
-
我们有 pc、笔记本电脑和打印机表,每个表有两列:型号和价格。目标是从所有表中找到最昂贵的模型。 MySQL。
-
@Kremchik - 改变你的结构。一张表,包含三列
(type, model, price),其中 type 包含ids 对应的{PC, Laptop, Printer}。然后,如果您添加例如monitor或其他类型,则无需添加新表并更新所有查询。 -
@Dems,我可以重构我的架构,但问题是我们可以给查询结果一个名称并从中选择吗?第一个查询中
t2的意义何在? -
@Kremchik - 许多 RDBMS 现在实现了公用表表达式。这些允许您定义一次子查询并在同一个外部查询中多次重复使用它。然而,MySQL 没有这种能力。就
Why do I need the T2 alias?而言,这仅仅是因为必须始终命名all 数据集。从技术上讲,你有SELECT MAX(t2.price),但你只是没有输入它。
标签: sql simplify simplification