如何在两个或多个连接表中获得重复结果?

时间:2011-08-09 09:34:22

标签: mysql sql duplicates

我有两张桌子:

  1. orders(id);
  2. order_items(id,order_id,item_id,quantity)
  3. 假设我已经选择了一个包含3个不同项目的订单X(A - 1单位,B - 2单位和C - 1单位)。

    我需要获得所有具有相同项目和完全相同数量的项目的订单(在这种情况下:A - 1单位,B - 2单位和C - 1单位,不多或不少:)),不包括订单X。

    我做了一个测试表转储,所以,我希望,因为你会更容易理解,我想得到什么:) http://nopaste.info/44eb93ae3d.html

    假设订单X = 1,所以期望的输出只是订单2,因为订单3只有一个项目,订单4和#1有相同的项目,但它还有一个项目额外,所以它不好:)

2 个答案:

答案 0 :(得分:1)

计算order_items表中每个订单的相同出现次数,然后与搜索到的订单的项目数进行比较:

SELECT i2.order_id
FROM order_items i1
    RIGHT OUTER JOIN order_items i2
        ON i2.item_id = i1.item_id 
        AND i2.quantity = i1.quantity
        AND i1.order_id = 1
WHERE i2.order_id  != 1
GROUP BY i2.order_id
HAVING COUNT(i1.order_id) = COUNT(*)
   AND COUNT(i1.order_id) = (SELECT COUNT(*) FROM order_items WHERE order_id = 1)

请注意,此查询假定(order_id, item_id)order_items表的键。

I have made a sample test here.

答案 1 :(得分:0)

select *
from orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN (select *
      from orders o2
      JOIN order_items oi2 ON o2.id = oi2.order_id
      WHERE o2.id = @X) sub
ON oi.quantity = sub.quantity
AND oi.item_id = sub.item_id
WHERE o.id <> @X

编辑:

select *
from orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN (select *
      from orders o2
      JOIN order_items oi2 ON o2.id = oi2.order_id
      WHERE o2.id = @X) sub
ON oi.quantity = sub.quantity
AND oi.item_id = sub.item_id
AND NOT EXISTS (select 1 
                from order_items 
                where order_id = o.id 
                and concat(item_id,quantity) not in (select concat(itemid,quantity)
                                                     from order_items
                                                     where order_id = o.id))
WHERE o.id <> @X