【发布时间】:2012-07-10 21:45:34
【问题描述】:
我有三个控制产品、颜色和尺寸的表格。产品可以有或没有颜色和尺寸。颜色可以有大小,也可以没有。
product color size
------- ------- -------
id id id
unique_id id_product (FK from product) id_product (FK from version)
stock unique_id id_version (FK from version)
title stock unique_id
stock
所有表中都存在的unique_id 列是串行类型(自动增量),它的计数器与三个表共享,基本上它作为它们之间的全局唯一ID。
它工作正常,但是当我必须选择基于unique_id 的某些字段时,我试图提高查询性能。
由于我不知道我正在寻找的unique_id 在哪里,我正在使用UNION,如下所示:
select title, stock
from product
where unique_id = 10
UNION
select p.title, c.stock
from color c
join product p on c.id_product = p.id
where c.unique_id = 10
UNION
select p.title, s.stock
from size s
join product p on s.id_product = p.id
where s.unique_id = 10;
有没有更好的方法来做到这一点?感谢您的任何建议!
编辑 1
根据@ErwinBrandstetter 和@ErikE 的回答,我决定使用以下查询。主要原因是:
1)unique_id在所有表中都有索引,我会得到很好的性能
2) 使用unique_id 我会找到产品代码,因此我可以使用另一个简单的连接获得我需要的所有列
SELECT
p.title,
ps.stock
FROM (
select id as id_product, stock
from product
where unique_id = 10
UNION
select id_product, stock
from color
where unique_id = 10
UNION
select id_product, stock
from size
where unique_id = 10
) AS ps
JOIN product p ON ps.id_product = p.id;
【问题讨论】:
-
为什么不使用 unique_id 加入所有表?
-
@03Usr,如果产品有多种颜色和至少一种尺寸,则查询将返回每种颜色的元组,而不是我所期望的一行。
-
我看不到您在查询中使用
unique_id的位置。 -
@ypercube,感谢您的建议,我已在
where子句中进行了更新。 -
请从标签中删除所有非特定数据库,除非它确实正在在所述特定数据库上运行。说“应该只使用标准 SQL”是一回事 ..
标签: sql postgresql postgresql-8.1