简体   繁体   English

使用SQL将结果限制为不同的列

[英]Limiting results to a distinct column with SQL

I am attempting to get a list of items along with the order information for each item. 我正在尝试获取商品列表以及每个商品的订购信息。 An order always has at least 1 item associated with it. 订单始终与至少一个项目相关联。 I want to limit this list to all of the items from 10 orders . 我想将此列表限制为10个订单中的所有项目。 As my query stands below, it gets 10 items . 正如我的查询所示,它得到10个项目 What is the best way to LIMIT this to 10 orders, while grabbing all of the items associated with these orders (be it 10 rows or 200 rows)? 抓取与这些订单关联的所有项目(10行或200行)的最佳方法是将其限制为10个订单?

SELECT o.*, i.*
FROM orders o, items i
WHERE i.order_id = o.id
LIMIT 0, 10

Much thanks! 非常感谢!

Try using a subselect where you limit the orders first. 尝试在首先限制订单的位置使用子选择。 In the outer select you then can fetch all items to these 10 orders. 然后,在外部选择中,您可以将所有项目提取到这10个订单中。

SELECT o.*, i.*
FROM items i, (SELECT * FROM orders LIMIT 0, 10) o
WHERE i.order_id = o.id
SELECT oo.*, i.*
FROM (
  SELECT *
  FROM orders o
  LIMIT 10
  ) oo , items i
WHERE i.order_id = oo.id

I don't know mysql but to take a guess 我不知道mysql,但要猜测一下

SELECT o.*, i.*
FROM orders o, items i
WHERE i.order_id = o.id and 
o.id in (select o.id from orders o limit 0, 10)

Something like this should work: 这样的事情应该起作用:

SELECT o.*, i.*
FROM items i INNER JOIN orders o ON o.id = i.order_id
WHERE o.order_id IN (
  SELECT o.id
  FROM orders
  LIMIT 0, 10
)
SELECT orders1.*, items.*
FROM
(select * from orders 
LIMIT 10) AS orders1
LEFT JOIN items ON orders1.id = items.order_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM