mysql - 通过具有一对多关系的桥接表加入

标签 mysql sql

我有一个 Products 表,它映射到一个桥接表,该表包含该产品所包含的所有项目,因此产品 A 可以由多个项目组成,也可以只由一个项目组成。 (OTM)

product_sub_item_bridge 看起来像这样,

+------------+----------------------------+
| product_id | client_sub_product_item_id |
+------------+----------------------------+
|        137 |                        332 |
|        138 |                        333 |
|        139 |                        334 |
|        140 |                        332 |
|        140 |                        335 |
+------------+----------------------------+

So say a client orders product 140, items 332 and 335 will be inserted into a table called client_sub_products which houses the relationship to the order and the items themselves that are stored in the client_sub_product_items table.

What I would like to do now is get all of the client_sub_products, group them by the client_order_id and maybe GROUP_CONCAT() the id's, and somehow join the Products table onto it via the bridging table, so that I can get a list containing the COUNT(), for all of theProducts that are comprised of those exact client_sub_product_items. Like so...

+--------------+---------------------+
| product_name | count(product_name) |
+--------------+---------------------+
|    Product A |                  15 |
|    Product B |                  25 |
+--------------+---------------------+

Here is what I have thus far,

SELECT GROUP_CONCAT(`client_sub_products`.`client_sub_product_item_id`) FROM `client_sub_products` LEFT JOIN `client_sub_product_items` ON `client_sub_product_items`.`id` = `client_sub_products`.`client_sub_product_item_id` GROUP BY `client_sub_products`.`client_order_id` ORDER BY `client_sub_products`.`client_order_id` ASC;

我似乎无法通过桥接表,我不确定如何通过桥接表将 client_sub_product_items 加入到 Products 中,因为有与不止一个 client_sub_product_item 相关的产品,我似乎在那里感到困惑。

我希望我已经充分解释了自己,而不是让每个人都感到困惑......如果我应该尝试澄清上面提到的任何事情,请告诉我。

最佳答案

如果子产品不是可订购的实体,为什么要将子产品关联到客户?为什么不直接将产品分配给客户,因为很容易从中为每个客户派生子产品?就目前而言,您没有明确的方法来确定示例中的子产品 332 是否与产品 137 或 140 相关。

关于mysql - 通过具有一对多关系的桥接表加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731508/

相关文章:

MySQL 左连接(我认为)

DB2 AS/400版本4的SQL查询限制

mysql - if else 在Mysql中加入

php - SimpleXML 解析多个同名标签

php - MySQL + PHP : Select all results from one table for each result of another

mysql - 连接两个具有不同格式的主键和外键的表

MySql 和 Wordpress 查询语法

mysql - 如何修改mysql存储过程中select的输出列名

sql - 如何以特定格式显示sql查询

javascript - 动态添加表单,可以插入到sql表中