我有一个 Products 表和一个 Orders 表,其定义方式使我可以执行如下 JOIN 查询,以返回特定用户订单为零的 Products。
此查询有效,但速度非常慢。
select * from products where id not in (select product_id from orders where user_id = 1)
问题是,如何更好更快地编写相同的查询?
最佳答案
不需要子查询:
SELECT p.product_id
FROM
Products p
LEFT JOIN Order o ON p.product_id = o.product_id AND o.user_id = @UserId
WHERE
o.order_id IS NULL -- or any other field that cannot be null on Order
编辑:为了提高性能,您可能还需要检查在 Order user_id 列和您的 id 上是否有索引(更有可能您在那里有它们,并且可能有聚簇索引,两者都值得检查)
关于php - mysql查询以获取用户没有订单的所有产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349931/