说我有一个表的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
。
另一个制约因素是,在相应的行processed
必须是true
的orderid
。
我的查询到目前为止
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
问:保持processed = true
为加盟条款的一部分被拖慢的查询。 如果我将它移动到WHERE子句,则表现要好得多。 这引起了我的兴趣, 我想知道这是为什么 。
而值列(主键和相应的外键列被索引value
, processed
等)则不是。
免责声明:我继承了这个DB结构和性能差异大约是6秒。