根据EAV中相关行中的值选择行

时间:2013-07-03 00:12:59

标签: mysql

我有两个表(EAV关系),Customeridname)和CustomerVarcharidcustomer_id,{ {1}},attribute_id)关系如下。

value hasMany Customer

CustomerVarchar belongsTo CustomerVarchar

我想根据Customer中具有特定值的两行在Customer中选择一行。更具体地说,我想在CustomreVarchar中检索具有以下条件的这两个关联行的行(必须在Customer中包含两个关联的行):

CustomerVarchar

这可能吗?

1 个答案:

答案 0 :(得分:2)

您可以使用以下命令从customer_id表中返回customerVarchar的所有属性和值:

select customer_id
from customerVarchar
group by customer_id
having 
  sum(case when attribute_id = 5 and value = 'John' then 1 else 0 end) > 0
  and sum(case when attribute_id = 7 and value = 'Doe' then 1 else 0 end) > 0;

然后,您可以将其加入到您的customer表中,以便向客户返回该数据:

select c.id, c.name
from customer c
inner join
(
  select customer_id
  from customerVarchar
  group by customer_id
  having 
    sum(case when attribute_id = 5 and value = 'John' then 1 else 0 end) > 0
    and sum(case when attribute_id = 7 and value = 'Doe' then 1 else 0 end) > 0
) v
  on c.id = v.customer_id;

请参阅SQL Fiddle with Demo