同一列上的多个条件

时间:2017-10-16 22:58:09

标签: sql oracle

如何在同一列上使用多个条件进行搜索。 T1有ID。

T2:

ID    T1_ID(FK)   Value
 1    1        Apple
 2    1        Orange
 3    1        Kiwi
 4    2        Orange
 5    2        Kiwi
 6    3        Pear
 7    3        Berry
 8    3        Orange
 9    4        Apple
 10   5        Apple
 11   5        Apple
 12   5        Kiwi

输出:

T2_ID(FK)   Value
1        Apple
1        Orange
1        Kiwi

select t2.t1_id, t2.value
from t1, t2
where t1.id = t2.id
and t2.value in ('Apple','Orange','Kiwi')
group by t1.id having count(t2.value)=3

此查询是否正确?它不会带来t2_id = 5因为#5与苹果和猕猴桃匹配,虽然苹果是重复的吗?

1 个答案:

答案 0 :(得分:0)

您无需加入t1,也需要COUNT(DISTINCT column_name)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE t2 (ID, T1_ID, Value ) AS
SELECT 1,    1,        'Apple' FROM DUAL UNION ALL
SELECT 2,    1,        'Orange' FROM DUAL UNION ALL
SELECT 3,    1,        'Kiwi' FROM DUAL UNION ALL
SELECT 4,    2,        'Orange' FROM DUAL UNION ALL
SELECT 5,    2,        'Kiwi' FROM DUAL UNION ALL
SELECT 6,    3,        'Pear' FROM DUAL UNION ALL
SELECT 7,    3,        'Berry' FROM DUAL UNION ALL
SELECT 8,    3,        'Orange' FROM DUAL UNION ALL
SELECT 9,    4,        'Apple' FROM DUAL UNION ALL
SELECT 10,   5,        'Apple' FROM DUAL UNION ALL
SELECT 11,   5,        'Apple' FROM DUAL UNION ALL
SELECT 12,   5,        'Kiwi' FROM DUAL;

查询1

select t1_id,
       LISTAGG( value, ',' ) WITHIN GROUP ( ORDER BY value ) As "values"
from   t2
where  value in ('Apple','Orange','Kiwi')
group by t1_id
having count( DISTINCT value) = 3

<强> Results

| T1_ID |            values |
|-------|-------------------|
|     1 | Apple,Kiwi,Orange |

查询2

您也可以使用集合来执行此操作:

CREATE TYPE STRINGLIST IS TABLE OF VARCHAR2(10);
/


SELECT *
FROM   (
  SELECT t1_id,
         CAST( COLLECT( value ORDER BY value ) AS STRINGLIST ) AS "values"
  FROM   t2
  GROUP BY t1_id
)
WHERE  STRINGLIST( 'Apple', 'Kiwi', 'Orange' ) SUBMULTISET OF "values"

<强> Results

| T1_ID |            values |
|-------|-------------------|
|     1 | Apple,Kiwi,Orange |