简化并更正以下查询
Simplify and correct following query
请问我该如何修复并可能简化这个 SQL 查询?
SELECT * FROM table WHERE
M IN (NULL,1) AND T IN (NULL,1) AND J IN (NULL,1) AND B IN (NULL,1)
AND (ISNULL(M,0)+ISNULL(T,0)+ISNULL(J,0)+ISNULL(B,0))<4
ORDER BY (ISNULL(M,0)+ISNULL(T,0)+ISNULL(J,0)+ISNULL(B,0)) DESC
table
包含 4 列 (M,T,J,B)
,只有 3 个可能的值 NULL, 0, 1
。
- 一线过滤器仅获取包含
NULL
或 1
. 的条目
- 第二行加法得到
M+J+T+B
的总和,只过滤if <4
.
- 三线
ORDER BY
同Total,M+J+T+B
.
错误#1582 - Incorrect parameter count in the call to native function 'ISNULL'
MySQL 等同于 ISNULL
是 IFNULL
... answered here
空值在 SQL 中表现得很奇怪。 任何 与 null 的比较测试将导致 FALSE,因此如果您在 where 子句中使用短语 Null=Null,则不会检索到任何内容,因为结果始终为 false。我会重写你的第二行,改用 IsNull 函数,
IsNull(M,1)*IsNull(T,1)*IsNull(J,1)*IsNull(B,1)>0
select * from (
select *, coalesce(M,0) M2, coalesce(T,0) T2, coalesce(J,0) J2, coalesce(B,0) B2
from table
where
(M is null or M=1) and
(T is null or T=1) and
(J is null or J=1) and
(B is null or B=1)
)x
where M2+T2+J2+B2 < 4
order by M2+T2+J2+B2 desc
Select
t.*,
coalesce(M,0) + coalesce(T,0) + coalesce(J,0) + coalesce(B,0) as calc
from table t
where
coalesce(M,0) in (0,1) and
coalesce(T,0) in (0,1) and
coalesce(J,0) in (0,1) and
coalesce(B,0) in (0,1) and
calc < 4
order by calc desc
请问我该如何修复并可能简化这个 SQL 查询?
SELECT * FROM table WHERE
M IN (NULL,1) AND T IN (NULL,1) AND J IN (NULL,1) AND B IN (NULL,1)
AND (ISNULL(M,0)+ISNULL(T,0)+ISNULL(J,0)+ISNULL(B,0))<4
ORDER BY (ISNULL(M,0)+ISNULL(T,0)+ISNULL(J,0)+ISNULL(B,0)) DESC
table
包含 4 列 (M,T,J,B)
,只有 3 个可能的值 NULL, 0, 1
。
- 一线过滤器仅获取包含
NULL
或1
. 的条目
- 第二行加法得到
M+J+T+B
的总和,只过滤if <4
. - 三线
ORDER BY
同Total,M+J+T+B
.
错误#1582 - Incorrect parameter count in the call to native function 'ISNULL'
MySQL 等同于 ISNULL
是 IFNULL
... answered here
空值在 SQL 中表现得很奇怪。 任何 与 null 的比较测试将导致 FALSE,因此如果您在 where 子句中使用短语 Null=Null,则不会检索到任何内容,因为结果始终为 false。我会重写你的第二行,改用 IsNull 函数,
IsNull(M,1)*IsNull(T,1)*IsNull(J,1)*IsNull(B,1)>0
select * from (
select *, coalesce(M,0) M2, coalesce(T,0) T2, coalesce(J,0) J2, coalesce(B,0) B2
from table
where
(M is null or M=1) and
(T is null or T=1) and
(J is null or J=1) and
(B is null or B=1)
)x
where M2+T2+J2+B2 < 4
order by M2+T2+J2+B2 desc
Select
t.*,
coalesce(M,0) + coalesce(T,0) + coalesce(J,0) + coalesce(B,0) as calc
from table t
where
coalesce(M,0) in (0,1) and
coalesce(T,0) in (0,1) and
coalesce(J,0) in (0,1) and
coalesce(B,0) in (0,1) and
calc < 4
order by calc desc