我正在尝试在两个表中提取具有匹配ID的唯一电子邮件。
SELECT line_items.order_id, line_items.id, orders.email, orders.name
FROM orders INNER JOIN
line_items
ON orders.id = line_items.order_id
WHERE line_items.order_id IN (SELECT DISTINCT email FROM orders WHERE status = 0 AND created_at BETWEEN '2018-01-10' AND NOW() )
LIMIT 50;
我知道我的错误是基于line_items.order_is是INT的事实,因此IN参数正在查找要匹配的另一个int列。但是,我不知道如何修改它以获得正确的结果。非常感谢任何和所有帮助。
答案 0 :(得分:1)
我正在尝试在两个表中提取具有匹配ID的唯一电子邮件。
如果您指的是不同的电子邮件,那么您的子查询似乎会这样做:
SELECT DISTINCT o.email
FROM o.orders
WHERE o.status = 0 AND o.created_at BETWEEN '2018-01-10' AND NOW();
因为订单应该至少包含一个订单项,所以我不明白为什么需要该表。
您的查询接近回答问题:“为最近订单状态为0的电子邮件提取所有订单”。如果这是你想要的:
SELECT li.order_id, li.id, o.email, o.name
FROM orders o INNER JOIN
line_items li
ON o.id = li.order_id
WHERE o.email IN (SELECT o2.email FROM orders o2 WHERE o2.status = 0 AND o2.created_at BETWEEN '2018-01-10' AND NOW() )
LIMIT 50;
答案 1 :(得分:1)
很难遵循,但我认为你想要:
SELECT sub.order_id, sub.line_item_id, sub.email, o.name
FROM
(SELECT o.email, MIN(o.id) AS order_id, MIN(i.id) AS line_item_id
FROM orders o
INNER JOIN line_items i
ON o.id = i.order_id
WHERE o.status = 0
AND o.created_at BETWEEN '2018-01-10' AND NOW()
GROUP BY o.email) sub
LEFT JOIN orders o
ON sub.order_id = o.id
在子查询中,选择每封电子邮件以及第一个订单ID和订单项ID。然后将此连接回订单以提取订单名称。这确实假设MIN(line_item)将显示每封电子邮件的MIN(order_id),因此如果这不是一个有效的假设,您必须告诉我。