查询,该产品仅提供具有特定阶段状态的产品

时间:2015-10-08 09:57:12

标签: mysql sql subquery

我有一个像这样的表结构:

产品

  • Id_products
  • 接受

PRODUCTS_STAGES

  • Id_products_stages
  • 名称

PRODUCTS_STAGES

  • Id_products_stages
  • 名称

PRODUCTS_STATUSES

  • Id_products_statuses
  • 名称
  • 颜色

PRODUCTS_STAGES_SET

  • Id_products_stages_set
  • Id_products(fk)
  • Id_products_stages(fk)

PRODUCTS_STATUSES_SET

  • Id_products_statuses_set
  • Id_products_statuses(fk)
  • Id_products_stages_set(fk)

在PRODUCTS_STATUSES中有4种状态(Id-name):

  • 1 - Notstarted
  • 2 - 已开始
  • 3 - 未完成
  • 4 - 完成

PRODUCTS_STAGES有6个阶段。

我有这样的查询:

SELECT p.Id_products FROM PRODUCTS AS p 
INNER JOIN (SELECT pss.Id_products FROM PRODUCTS_STAGES_SET AS pss
                    INNER JOIN PRODUCTS_STATUSES_SET AS pss2 ON pss.Id_products_stages_set = pss2.Id_products_stages_set 
                    WHERE pss2.Id_products_statuses IN (1,2,3)
                    GROUP BY pss.Id_products) ps
ON p.Id_products = ps.Id_products

此查询为我提供的产品至少一个阶段已完成

现在我想要一个查询,它给我的产品只有特定的阶段状态。例如,我希望产品具有 stage2 = Started

1 个答案:

答案 0 :(得分:0)

SELECT p.Id_products FROM PRODUCTS AS p 
INNER JOIN (SELECT pss.Id_products FROM PRODUCTS_STAGES_SET AS pss
                    INNER JOIN PRODUCTS_STATUSES_SET AS pss2 ON pss.Id_products_stages_set = pss2.Id_products_stages_set 
                    WHERE pss2.Id_products_statuses = 2
                    GROUP BY pss.Id_products) ps
ON p.Id_products = ps.Id_products