这个 table 的最佳 SQL 声明?
Best SQL statement for this table?
我 table 有 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 的记录。
你可以这样做:
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);
我应该注意到,尝试使用列后缀实现数组的 table 通常表示数据布局不佳。您应该考虑使用 table 每个 "id".
有一个 "f" 值
编辑:
如果 Firebird 确实将 IN
值限制为常量,那么代码会更冗长。
where (f1 = 1 or f2 = 1 or . . . ) and
(f1 = 2 or f2 = 2 or . . . ) and
(f1 = 3 or f2 = 3 or . . . )
使用常见 table 表达式的查询:
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
我 table 有 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 的记录。
你可以这样做:
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);
我应该注意到,尝试使用列后缀实现数组的 table 通常表示数据布局不佳。您应该考虑使用 table 每个 "id".
有一个 "f" 值编辑:
如果 Firebird 确实将 IN
值限制为常量,那么代码会更冗长。
where (f1 = 1 or f2 = 1 or . . . ) and
(f1 = 2 or f2 = 2 or . . . ) and
(f1 = 3 or f2 = 3 or . . . )
使用常见 table 表达式的查询:
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