假设我有一张order
号的桌子
id | clientid | type | amount | itemid | date
---|----------|------|--------|--------|-----------
23 | 258 | B | 150 | 14 | 2012-04-03
24 | 258 | S | 69 | 14 | 2012-04-03
25 | 301 | S | 10 | 20 | 2012-04-03
26 | 327 | B | 54 | 156 | 2012-04-04
-
clientid
是返回client
表的外键 -
itemid
是返回item
表的外键 -
type
只是B
或S
-
amount
是一个整数
还有一张processed
号桌
id | orderid | processed | date
---|---------|-----------|---------
41 | 23 | true | 2012-04-03
42 | 24 | true | 2012-04-03
43 | 25 | false | <NULL>
44 | 26 | true | 2012-04-05
我需要得到order
的所有行,对于相同的clientid
,在相同的date
上有相反的type
值.记住type
只能有两个值中的一个——B
或S
.在上面的示例中,这将是第23
行和第24
行.
另一个约束是,对于orderid
,processed
中对应的行必须是true
.
到目前为止我的问题
SELECT c1.clientid,
c1.date,
c1.type,
c1.itemid,
c1.amount,
c2.date,
c2.type,
c2.itemid,
c2.amount
FROM order c1
INNER JOIN order c2 ON c1.itemid = c2.itemid AND
c1.date = c2.date AND
c1.clientid = c2.clientid AND
c1.type <> c2.type AND
c1.id < c2.id
INNER JOIN processed p1 ON p1.orderid = c1.id AND
p1.processed = true
INNER JOIN processed p2 ON p2.orderid = c2.id AND
p2.processed = true
QUESTION:将processed = true
保留为join子句的一部分会减慢查询速度.如果我把它移到WHERE子句,那么性能会更好.这引起了我的兴趣和兴趣.
主键和相应的外键列被索引,而值列(value
、processed
等)没有索引.
Disclaimer: I have inherited this DB structure and the performance difference is roughly 6 seconds.