我有以下SQL:
SELECT id FROM order o
INNER JOIN order_payment p ON p.parent_id=o.entity_id
WHERE o.state='new'
AND o.created_at BETWEEN '2013-05-14'
AND '2013-10-11 00:19:09'
AND p.method IN ('paymethod_a', 'paymethod_b', 'paymethod_c')
--AND o.id NOT IN (SELECT id FROM order o
--INNER JOIN payment_method pm ON pm.order_id=o.id
--WHERE o.created_at BETWEEN '2013-05-14' AND '2013-10-11 00:19:09')**
在评论部分,我不想获得表support_method.order_id(外键)上匹配的任何id。 但是现在,系统更新改变了一些事情:现在我希望在注释区域得到相同的结果,PLUS:如果payment_method寄存器的'status = 0'列,我也必须得到那个id,如果订单那就没关系。 id在payment_method.order_id(外键)上。
我厌倦了SQL,任何人都可以帮助我吗? 谢谢!
答案 0 :(得分:1)
通常,NOT IN(子选择查询)的性能很差。相反,如果另一个表为NULL(表示不存在),则执行LEFT-JOIN并接受记录要好得多。如果您希望包含OTHER特殊条件,这也有助于您的条件。类似的东西:
SELECT
o.id
FROM
order o
JOIN order_payment op
ON o.entity_id = op.parent_id
AND op.method in ('paymethod_a', 'paymethod_b', 'paymethod_c')
LEFT JOIN payment_method pm
on o.id = pm.order_id
where
o.state='new'
AND o.created_at BETWEEN '2013-05-14' AND '2013-10-11 00:19:09'
AND ( pm.order_id IS NULL
OR pm.status = 0 )
答案 1 :(得分:0)
考虑到您要加入3个不同的表并包含状态0
SELECT id FROM order o
INNER JOIN order_payment p ON p.parent_id=o.entity_id
INNER JOIN payment_method t3 ON t3.order_ID = o.orderID
WHERE o.state='new'
AND o.created_at BETWEEN '2013-05-14'
AND '2013-10-11 00:19:09'
--query modified,if there are only one parameters,Function 'IN' is not supported
AND p.method = 'payment_method'
--you never exclude status = 0 in payment_method table, so nothing is needed to do at all