mysql - SQL 产品组大小和颜色一起

标签 mysql sql join

我有以下 3 个表,我想用它们将 2 行组合在一起以使其成为单行,因为它们属于一个产品。

Order
--------
order_id

Order_product
-------------
order_id
order_product_id

order_product_attribute
------------------------------
orders_products_attributes_id
order_id
product_id
products_options
options_id  

=== Data ===
|1|2|7|Size      |1|270
|2|2|7|Colour(s) |3|99202
|3|2|8|Size      |1|270
|4|2|8|Colour(s) |3|47768

我想要的结果需要如下:

order_id, product_id, size_options_id (option_id for size), colour_options_id (option_id for color)

size_options_id 是可选的,这意味着它对于某些产品甚至可能不存在。

我不确定我需要使用什么连接来一次性获得这个结果,而不是通过 PHP 检查来完成。

最佳答案

假设你的表如下:

create table order (order_id int);
insert into order values(2);

create table order_product (order_id int, order_product_id int);
insert into order_product values (2,7);
insert into order_product values (2,8);

create table order_product_attribute (orders_products_attributes_id int, order_id int, product_id int, products_options int, options_id int);
insert into order_product_attribute values (1, 2, 7, 1, 270);
insert into order_product_attribute values (2, 2, 7, 3, 99202);
insert into order_product_attribute values (3, 2, 8, 1, 270);
insert into order_product_attribute values (4, 2, 8, 3, 47768);

desired output:

2  7  270 99202
2  8  270 47768

您应该使用两个左连接。它应该是这样的:

select 
   o.order_id, 
   op.product_id, 
   opas.options_id as size_options_id, 
   opac.options_id as colour_options_id 
from my_order o
join order_product op on op.order_id=o.order_id
left join order_product_attribute opas 
   on opas.order_id=o.order_id 
   and opas.product_id=op.product_id
   and opas.product_options=1
left join order_product_attribute opac 
   on opac.order_id=o.order_id 
   and opac.product_id=op.product_id
   and opac.product_options=3

第一个左连接仅与这些包含大小的行连接。
第二个左连接是连接包含颜色的行。

你可以在SQLFiddle中看到它

关于mysql - SQL 产品组大小和颜色一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28475992/

相关文章:

php - 如何显示存储在 MySql 数据库中的 BLOB 图片?

mysql - 加入 2 个 MySQL 表以列出所有帖子并查找特定用户关注的用户(登录的 INN 用户)

sql - 连接具有重复项的 SQL Server 表

mysql - DECLARE CONTINUE HANDLER FOR NOT FOUND SET 变量不起作用

mysql - 选择外行仅匹配单个值的行

消息系统的Mysql查询。一个我想不通的小错误

sql - Knex on constraint upsert 冲突

sql - 多列索引效率

c# - 从 C# 自动打开 SSMS

MYSQL:如果找不到任何记录,则如何根据 id 连接表,然后使用默认值