【发布时间】:2016-01-13 11:37:43
【问题描述】:
我想在同一张表上进行内部连接,即 product_attributes 我想要 prod_value = gender 和 prod_attr=Male 和 maingroup = Pants。这意味着,我想要所有性别为男性且属于 Pants 的产品。我什至想打印 prodgroup 并加入需要prod_name 的product_master 表。我怎样才能做到这一点?
表 1:Product_attributes
+----+------------+-----------+------------+
| id | prod_style | prod_attr | prod_value |
+----+------------+-----------+------------+
| 1 | 0010 | gender | Male |
| 2 | 0010 | maingroup | Pants |
| 3 | 0010 | prodgroup | Pants_Abc |
| 4 | 0010 | Blue | color |
| 5 | 0011 | gender | Male |
| 6 | 0011 | maingroup | Pants |
| 7 | 0011 | prodgroup | Pants_Pqr |
| 8 | 0012 | gender | Female |
| 9 | 0012 | maingroup | Pants |
| 10 | 0012 | prodgroup | Pants |
| 11 | 0013 | gender | Female |
| 12 | 0013 | maingroup | Jackets |
+----+------------+-----------+------------+
表 2:Product_master
+----+------------+-----------+
| id | prod_style | prod_name |
+----+------------+-----------+
| 1 | 0010 | ABC |
| 2 | 0011 | PQR |
| 3 | 0012 | XYZ |
| 4 | 0013 | LMN |
+----+------------+-----------+
我已经尝试过这个解决方案:
select
*
from
product_master pm
INNER JOIN (select
*
from
product_attributes
where
prod_value='prodgroup'
and prod_style in(select
prod_style
from
product_attributes
where
prod_attr ='pants'
and prod_value='mainGroup'
and prod_style in(select
prod_style
from
product_attributes
where
prod_attr='Male'
)
)
) p ON pm.prod_style = p.prod_style
ORDER By
prod_name
使用我的解决方案,我得到了输出,但不知道其编写查询的方式是否正确。
使用上述解决方案输出:
+-----------+------------+-----------+-------------+-----------+-----------+
| id | prod_style | prod_name | prod_style | prod_attr | prod_value|
+-----------+------------+-----------+-------------+-----------+-----------+
| 1 | 0010 | ABC |0010 |Pants_Abc |prodgroup |
| 2 | 0011 | PQR |0011 |Pants_Pqr |prodgroup |
| 3 | 0012 | XYZ |0012 |Pants |prodgroup |
| 4 | 0013 | LMN |0013 |skinny |prodgroup |
+-----------+------------+-----------+-------------------------------------+
【问题讨论】:
-
@piya 你能解释一下你想要什么吗?我在做这个工作! (我想要所有性别为男性且属于裤子的产品)
-
我上面已经解释过了。我想获取所有性别为男性且主组为裤子的产品
标签: mysql sql-server join