这个表的最佳SQL语句?

时间:2017-05-25 11:37:25

标签: sql firebird

我有9个字段ID的表,F1..F8。

一些数据的例子:

id f1 f2 f3 f4 f5 f6 f7 f8
1   1  2  3  0  0  0  0  0
2   0  1  0  3  2  0  0  0
3   4  0  5  2  1  0  0  0  
4   0  0  0  0  0  0  1  4
5   2  0  0  0  0  1  3  0
6   2  0  0  0  0  1  0  8
7   2  0  0  0  0  1  0  3
.
.
.

我怎样才能select * from table where F1...F8 in value (1,2,3)? 此查询的结果必须包含ID为1,2,5,7的记录。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

select t.*
from t
where 1 in (f1, f2, f3, f4, f5, f6, f7, f8) and
      2 in (f1, f2, f3, f4, f5, f6, f7, f8) and
      3 in (f1, f2, f3, f4, f5, f6, f7, f8);

我应该注意,尝试使用列后缀实现数组的表通常表示数据布局不佳。你应该考虑使用一个带有一个" f"值" id"。

编辑:

如果Firebird确实将IN值限制为常量,则代码更详细。

where (f1 = 1 or f2 = 1 or . . . ) and
      (f1 = 2 or f2 = 2 or . . . ) and
      (f1 = 3 or f2 = 3 or . . . )

答案 1 :(得分:0)

将查询与公用表表达式一起使用:

WITH t AS
  (
    SELECT id, f1 AS f from tbl
    UNION ALL
    SELECT id, f2 AS f from tbl
    UNION ALL
    SELECT id, f3 AS f from tbl
    UNION ALL
    SELECT id, f4 AS f from tbl
    UNION ALL
    SELECT id, f5 AS f from tbl
    UNION ALL
    SELECT id, f6 AS f from tbl
    UNION ALL
    SELECT id, f7 AS f from tbl
    UNION ALL
    SELECT id, f8 AS f from tbl
  )
SELECT
  t1.id
FROM
  t t1
  JOIN t t2 ON t2.id = t1.id
  JOIN t t3 ON t3.id = t2.id
WHERE
  t1.f IN (1, 2, 3)
  AND
  t2.f IN (1, 2, 3)
  AND
  t3.f IN (1, 2, 3)
  AND
  t1.f <> t2.f
  AND
  t2.f <> t3.f