Best SQL statement for this table?

旧时模样 提交于 2019-12-02 07:15:36

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

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