[英]Using join in place of this sub-query in MySQL
I have a table by the following structure and records, All i want to do is to just extract orderid of those records whose status id is either 1 or 2, i want to exclude all orderid with statusid=3, , problem is that orderid 106 has both status 1 and 3... I have written a sub-query which serves the purpose..我有一个由以下结构和记录组成的表,我要做的就是提取那些状态 id 为 1 或 2 的记录的 orderid,我想排除所有 statusid=3 的 orderid,问题是 orderid 106同时具有状态 1 和 3...我写了一个子查询来达到目的..
select *
from orders_status_history
where orders_id NOT IN
(select orders_id
from orders_status_history
where orders_status_id = 3)
is there any other way of doing this without using sub-queries as i have heard it hampers performance.有没有其他方法可以在不使用子查询的情况下执行此操作,因为我听说它会妨碍性能。 As my query can return thousands of rows as well.
因为我的查询也可以返回数千行。
id order-id status-id
1 1 1
2 2 1
3 105 1
4 106 1
5 106 3
6 108 1
7 109 1
8 109 2
Any help or suggestion will be highly appreciated..Thanks in advance..任何帮助或建议将不胜感激..在此先感谢..
You may do that:你可以这样做:
SELECT osh.*
FROM orders_status_history osh
LEFT JOIN
orders_status_history oshd
ON oshd.orders_id = osh_orders_id
AND oshd.orders_status_id = 3
WHERE oshd.orders_id IS NULL
However, if you have an index on order_status_history (orders_id, orders_status_id)
, then the NOT IN
query is just as fine.但是,如果您在
order_status_history (orders_id, orders_status_id)
上有一个索引,那么NOT IN
查询也一样好。
You may want to read this:您可能想阅读以下内容:
I wonder why you use sub query while you can use the following query我想知道为什么您使用子查询,而您可以使用以下查询
select orders_id from orders_status_history where orders_status_id <> 3
Please try this, and I hope it helps请试试这个,希望对你有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.