sql搜索多个值

时间:2018-12-17 22:46:59

标签: sql

我有一个customer表和一个attribute表。

attribute表存储每个客户拥有的属性,以便将要添加到客户的属性作为新行输入。

我需要找到同时具有'cash sale'属性和'email statement'属性的客户。

我尝试过:

select distinct customer
where attributename='cash sale'
and attributename='email statement'

4 个答案:

答案 0 :(得分:3)

使用EXISTS检查客户在属性表中是否具有特定属性:

SELECT 
  customerid, customername
FROM
  customers c
WHERE
  EXISTS (
    SELECT 1 FROM attributes a WHERE a.customerid = c.customerid AND a.attributename = 'cash sale'
  )
  AND 
  EXISTS (
    SELECT 1 FROM attributes a WHERE a.customerid = c.customerid AND a.attributename = 'email statement'
  )

假设customers.customerid是id,attributes.customerid是外键。

答案 1 :(得分:2)

您要使用从表JOIN到表customer的两个attribute,每个必须对客户可用的属性使用一个。

假设...

  • customer上有一个名为id的列,用于唯一标识客户
  • attribute的列名为customer_id,是customer的外键

...这是回答您问题的查询:

SELECT c.id
FROM 
    customer c
    INNER JOIN attribute a1
        ON  a1.customer_id = c.id 
        AND a1.attributename = 'cash sale'
    INNER JOIN attribute a2
        ON  a2.customer_id = c.id
        AND a2.attributename = 'email statement'

NB:由于idcustomer表中的唯一字段,因此不需要DISTINCT

答案 2 :(得分:0)

如果没有有关数据库架构的更多信息,很难准确回答。 无论如何,您都需要在两个表上加入并进行扇出。

例如(以Oracle语法):

     Name     Value 1     Value 2     Value 3    Value 4    Value 5
0     A          1          3           4           5          2
1     B          4          5           6           6          7
2     C          7          1           3           8          0
3     D          2          3           6           9          8
4     E          5          10          11          4          6
5     F          7          1           0           7          8

此语句将为每个客户返回一或两行,并将不同的属性附加到重复的客户列中:

select <customer columns that you want> from customers c
inner join attributes a
on c.customer_id = a.customer_id
where attributename = 'cash sale'
or attributename = 'email statement'
having count(1) = 2
group by <customer columns that you want>

“具有”语句将返回的数据限制为只有两行(每个属性一个)的客户,“分组依据”语句将两行合并为一。

这假定:

  • customers表中有一个唯一的customer_id主键列。
  • customer和attribute表之间的关系是一对多关系。

答案 3 :(得分:0)

我假设在属性表中,(customerId,attributename)是唯一的

 select *
    from customer c
    where c.customerId IN (
        select a.customerId
        from attribute a
        where a.attributename = 'cash sale'
        or a.attributename = 'email statement'
        group by a.customerId
        having count(a.attributename) = 2
    );
相关问题