Best SQL statement for this table?

怎甘沉沦 提交于 2020-01-22 00:00:51

问题


I have table with 9 fields ID, F1..F8.

An example of some data:

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
.
.
.

How can I select * from table where F1...F8 in value (1,2,3)? The result of this query must have records with id 1,2,5,7.


回答1:


Use query with common table expression:

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



回答2:


You can do:

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);

I should note that a table that attempts to implement an array using column suffixes usually indicates a poor data layout. You should consider using a table with one "f" value per "id".

EDIT:

If Firebird really does limit the IN values to constants, then the code is more verbose.

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


来源:https://stackoverflow.com/questions/44179634/best-sql-statement-for-this-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!