如何从表中选择条件(和)用于某些行

时间:2014-10-21 12:37:11

标签: oracle

我正在使用oracle 11。

我有一些表

+---------+-----------+--------+--------+
| attr_id | record_id | value1 | value2 |
+---------+-----------+--------+--------+
|       1 |         1 | 2      | null   |
|       2 |         1 | null   | 6      |
|       3 |         1 | 4      | null   |
|       1 |         2 | null   | 4      |
+---------+-----------+--------+--------+

我想选择这样:

select record_id from table
where ((attr_id = 1 and value1 = 2) and (attr_id = 3 and value1 = 4))

我希望输出record_id = 1。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,您想要选择record_id 两者

  • (attr_id = 1 and value1 = 2)是一行
  • (attr_id = 3 and value1 = 4)在另一行。

这里不能在表SELECT子句中使用简单的WHERE,因为它会检查同一行中的条件,这是不能满足的(attr_id不能等于同一行中的13。所以your query无效。

但是,有一个解决方案。您将需要一个self-JOIN,为给定的record_id生成(attr_id,value)对的所有组合。

我认为你对SQL比较陌生,我将分几步建立我的答案:

自连接

正如我之前所说,我们首先要自己加入你的桌子:

select t1.attr_id as attr_id_1,
       t1.value1 as value1_1,
       t2.attr_id as attr_id_2,
       t2.value1 as value1_2,
       record_id
from t as t1
join t as t2 using(record_id)
制造

ATTR_ID_1   VALUE1_1    ATTR_ID_2   VALUE1_2    RECORD_ID
1           2           1           2           1
2           (null)      1           2           1
3           4           1           2           1
1           2           2           (null)      1
2           (null)      2           (null)      1
3           4           2           (null)      1
1           2           3           4           1       <---------
2           (null)      3           4           1
3           4           3           4           1
1           (null)      1           (null)      2

(实例:http://sqlfiddle.com/#!2/73a490/6

如您所见,具有相同record_id的所有行组合都在该结果集中。包括一行与自身的组合。请注意我已经发现了你正在寻找的行。

获取“正确”记录

现在,让record_id同时拥有(attr_id = 1 and value1 = 2) (attr_id = 3 and value1 = 4)非常容易。您只需要使用正确的表别名为列添加前缀:

select t1.attr_id as attr_id_1,
       t1.value1 as value1_1,
       t2.attr_id as attr_id_2,
       t2.value1 as value1_2,
       record_id
from t as t1
join t as t2 using(record_id)
where t1.attr_id = 1 and t1.value1 = 2
  and t2.attr_id = 3 and t2.value1 = 4

产:

ATTR_ID_1   VALUE1_1    ATTR_ID_2   VALUE1_2    RECORD_ID
1           2           3           4           1

(见http://sqlfiddle.com/#!2/73a490/8

最终答案

最后,很容易抛出一点查询以仅返回所需的值:

select record_id
from t as t1
join t as t2 using(record_id)
where t1.attr_id = 1 and t1.value1 = 2
  and t2.attr_id = 3 and t2.value1 = 4