【发布时间】:2013-12-23 11:09:47
【问题描述】:
我有两张表 Sell 和 Purchase。我的查询给了我想要的结果,我对它的性能很小心,所以如果它可以更好,请指导我。我的桌子是:
Table Sell
UserId | ProductId | ProductName | ProductPrice
1 | p_101 | Cycle | 500
1 | p_121 | Car | 500000
2 | p_111 | Cycle | 5000
餐桌购买
UserId | ProductId | ProductName | ProductPrice
1 | p_109 | CellPhone | 150
2 | p_121 | Car | 500000
3 | p_111 | Book | 15
所需的输出表
Type | ProductId | ProductName | ProductPrice
Sell | p_101 | Cycle | 500
Sell | p_121 | Car | 500000
Purchase| p_109 | CellPhone | 150
工作查询:
SELECT type, P1.ProductId, P1.ProductName, P1.ProductPrice
FROM
(
SELECT s.UserId, 'Sell' as type, s.ProductId, s.ProductName, s.ProductPrice FROM [Sell] s
UNION
SELECT p.userid, 'Purchase' as type, p.ProductId, p.ProductName, p.ProductPrice FROM [Purchase] p
) as P1
WHERE userid=1
【问题讨论】:
-
你有查询执行计划吗?有什么索引吗?这是ms-sql吗?这可能更适合 dba.stackexchange.com... 这些表上的行数?
-
只是一个想法:将
WHERE userid=1移动到内部选择 -
@rene, nop... 我没有查询执行和索引。
-
要查看计划,请在查询前加上 Explain 并执行它。说唯一有用的索引是产品和销售中的 UserId,因为它是 where 子句中的唯一因素。
标签: sql sql-server query-optimization