0

我有两个表(EAV 关系),Customer( id, name) 和CustomerVarchar( id, customer_id, attribute_id, value) 关系如下。

Customer有很多CustomerVarchar

CustomerVarchar属于Customer

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

row 1 has `attribute_id`= 5 and `value`=`John`

row 2 has `attribute_id`= 7 and `value`=`Doe`

这可能吗?

4

1 回答 1

2

You can use the following to return the customer_id from the customerVarchar table with all of the attributes and values:

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;

Then you can JOIN this to your customer table to return the customers with that data:

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;

See SQL Fiddle with Demo

于 2013-07-03T00:30:04.940 回答