仅选择前两个项目并订购

时间:2017-03-01 09:10:07

标签: mysql

我需要你的帮助,我有3个表ORDERS,ORDER_ITEM,ORDER_ITEM_LINE。

CREATE TABLE orders
(`id` int, `date` datetime)
;

INSERT INTO orders
(`id`, `date`)
VALUES
(78, '2017-01-03 00:00:00'),
(79, '2017-02-03 00:00:00'),
(80, '2017-03-03 00:00:00'),
(81, '2017-04-03 00:00:00'),
(82, '2017-05-03 00:00:00'),
(83, '2017-06-03 00:00:00'),
(84, '2017-07-03 00:00:00')

CREATE TABLE order_item
(`id` int, `fk_o_id` int, `sku` int)
;

INSERT INTO order_item
(`id`, `fk_o_id`, `sku`)
VALUES
(10, 78, 123),
(11, 79, 124),
(12, 79, 125),
(13, 80, 126),
(14, 82, 127),
(15, 82, 128),
(16, 82, 129)
;


CREATE TABLE order_item_line
(`id` int, `fk_oi_id` int, `line_id` int)
;

INSERT INTO order_item_line
(`id`, `fk_oi_id`, `line_id`)
VALUES
(33, 10, 1),
(34, 11, 1),
(35, 12, 2),
(36, 13, 1),
(37, 14, 1),
(38, 15, 2),
(39, 16, 3)

我想显示所有包含2个或2个以上商品的订单,但只显示前两个,所以它将是line_id - 1和2。

结果应该如下:

Outcome

如果您有任何想法,请提前感谢您。

1 个答案:

答案 0 :(得分:0)

要获得所需的结果,您需要创建另一个表。在这个例子中,我创建了一个名为TESTQUERY的表,并插入数据来计算订单ID出现的次数

表格创建

CREATE TABLE TESTQUERY
(`id` int, `count` int)

数据进入测试表

INSERT INTO TESTQUERY
(
SELECT o.id, COUNT(o.id) as count FROM orders o 
JOIN order_item oi ON oi.fk_o_id = o.id 
JOIN order_item_line oil ON oil.fk_oi_id = oi.id
GROUP BY o.id
)

然后,我使用下面的查询查询所有数据库,并返回了您想要的结果

SELECT o.id, oi.sku, oil.line_id FROM orders o
JOIN order_item oi ON oi.fk_o_id = o.id
JOIN order_item_line oil ON oil.fk_oi_id = oi.id
JOIN TESTQUERY t ON t.id = o.id
WHERE t.count > 1 AND oil.line_id < 3

我希望这会有所帮助