代码之家  ›  专栏  ›  技术社区  ›  omatica

MySQL查询帮助(EAV表)

  •  1
  • omatica  · 技术社区  · 16 年前

    我有以下查询来检索对特定问题回答“是”的客户。” 或 “不,回答另一个问题。

    SELECT customers.id
    FROM customers, responses
    WHERE (
    (
    responses.question_id = 5
    AND responses.value_enum = 'YES'
    )
    OR (
    responses.question_id = 9
    AND responses.value_enum = 'NO'
    )
    )
    GROUP BY customers.id
    

    很好用。但是,我希望更改查询以检索对特定问题回答“是”的客户。” 和 “对另一个问题回答“否”。

    我对如何实现这一点有什么想法吗?

    PS-上表中的响应采用EAV格式,即一行代表一个属性,而不是一列。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Mark Byers    16 年前

    我假设您在响应表中有一个名为customer_id的列。尝试将响应表与其自身联接:

    SELECT Q5.customer_id
    FROM responses Q5
    JOIN responses Q9 ON Q5.customer_id = Q9.customer_id AND Q9.question_id = 9
    WHERE Q5.question_id = 5
    AND Q5.value_enum = 'YES'
    AND Q9.value_enum = 'NO'
    
        2
  •  0
  •   Donnie    16 年前

    大致如此:

    SELECT distinct
      c.id
    FROM 
      customers c
    WHERE
      exists (select 1 from responses r where r.customer_id = c.id and r.response_id = 5 and r.value_enum = 'YES')
      and exists (select 1 from responses r2 where r2.customer_id = c.id and r2.response_id = 9 and r2.value_enum = 'NO')
    

    我对失踪者作了假设 join 条件,修改为适合您的模式。