简体   繁体   English

MySQL正确的一对多关系包括和不包括右表的联接方法

[英]MySQL proper join method for one-to-many relationship including and excluding right table

I've been trying to solve this MySQL issue...half of the problem is wording my question, I apologize if this has been solved before, I did a lot of searching but wasn't able to find a solution. 我一直在尝试解决这个MySQL问题...问题的一半是我的问题,如果在此之前已经解决,我深感抱歉,我做了很多搜索,但找不到解决方案。

I have two tables, called orders and order_items Each order can contain many order items. 我有两个表,分别称为orders和order_items。每个订单可以包含许多订单项。

I need to do a search that returns orders that contain only one order item and not another, then vice versa. 我需要进行搜索,以返回仅包含一个订单项而不包含另一个订单项的订单,反之亦然。

To illustrate this point: 为了说明这一点:

Table orders 表订单

order_id
1
2
3

Table order_items 表order_items

order_item_id | order_item_type | order_id
1             | A               | 1
2             | A               | 2
3             | B               | 2
4             | B               | 3

What I need to do is to get orders that include only item A, only item B, and both. 我需要做的是获取仅包含项目A,仅包含项目B以及两者都包含的订单。

As you can see Only Item A should return order 1, only item B should return order 3, and both should return order 2. 如您所见,只有项目A应该返回订单1,只有项目B应该返回订单3,并且两者都应该返回订单2。

Despite all my best attempts I cannot get anything working. 尽管我尽了最大的努力,但我什么也做不了。 Here is the current attempt at returning orders with ONLY item A 这是目前仅退还项目A的订单的尝试

SELECT *
    FROM orders
    LEFT OUTER JOIN order_items
    ON order_items.order_id = orders.order_id
    WHERE order_items.order_item_type IN ('A')
    AND order_items.order_item_type NOT IN ('B')
    GROUP BY orders.order_id

As an experienced person can probably guess looking at my attempt, this returns both order 1 and order 2. I think this could probably be done with a subquery, but I believe it can be done with a proper join...just not sure how to do it. 作为有经验的人可能会猜一下我的尝试,这将同时返回顺序1和顺序2。我认为可以通过子查询来完成,但是我相信可以通过适当的联接来完成...只是不确定如何去做吧。 Thank you! 谢谢!

when selected single order_item: 当选择单个order_item时:

SELECT i.* FROM order_items i
WHERE i.order_item_type = 'A' AND
  (SELECT COUNT(order_id) FROM order_items WHERE order_id = i.order_id) = 1

selected two order_item: 选择了两个ord​​er_item:

SELECT i.* FROM order_items i
WHERE i.order_item_type IN ('A', 'B') AND
  (SELECT COUNT(order_id) FROM order_items WHERE order_id = i.order_id) = 2

and join orders table as you like. 并根据需要加入orders表。

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

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