我以前的问题和解决方案:
Get max and min from fields
这个工作正常,但是我希望在这个例子中跳过0和NULL。
例如:

First:
id | title
1  | aaa
2  | bbb
3  | ccc

Second:
id | first_id | one | two    | three | four
1  |    1     | 3   | 0      | 4     | 6
2  |    2     | 4   | 4      | 1     | 2
3  |    3     | 1   | NULL   | 3     | 4

这应该告诉我:
id | title | min | max
1  | aaa   |  3  | 6
2  | bbb   |  1  | 4
3  | ccc   |  1  | 4

而不是:
id | title | min | max
1  | aaa   |  0  | 6
2  | bbb   |  1  | 4
3  | ccc   |  0  | 4

在上一个问题的哪个示例中,实现skip 0和NULL的最佳方法?

最佳答案

把这些放进你的条款里

SELECT
    f.id,
    f.title
    MIN(LEAST(greatest(coalesce(s.one,0),1), greatest(coalesce(s.two,0),1), greatest(coalesce(s.three,0),1), greatest(coalesce(s.four,0),1))) as min,
    MAX(GREATEST(greatest(coalesce(s.one,0),1), greatest(coalesce(s.two,0),1), greatest(coalesce(s.three,0),1), greatest(coalesce(s.four,0),1))) as max
FROM
    First f
        INNER JOIN Second s
        on f.id = s.first_id
GROUP BY
    f.id,
    f.title

您可以使用coalesce(fieldName, 1)将空值转换为1。
同样,正如您在上一个问题中所说,这是一个可怕的使用查询来强制回答。您应该更改数据库的布局。
编辑:我已经删掉了你想要的数据,但是在你看之前,要知道如果我的一个同事写了这样的脚本,他会被当场解雇。这是可怕的,不应该使用。
select
    f.id,
    f.title,
    (select min(z.myVal) from
        (
select
    b.id,
    b.first_id,
    b.one as myVal
from
    second b
where
    b.one is not null
    and b.one > 0
union
select
    b.id,
    b.first_id,
    b.two as myVal
from
    second b
where
    b.two is not null
    and b.two > 0
union
select
    b.id,
    b.first_id,
    b.three as myVal
from
    second b
where
    b.three is not null
    and b.three > 0
union
select
    b.id,
    b.first_id,
    b.four as myVal
from
    second b
where
    b.four is not null
    and b.four > 0
        ) z
    where
    f.id=z.first_id) as miniVal,
    greatest(
        coalesce(s.one,0),
        coalesce(s.two,0),
        coalesce(s.three,0),
        coalesce(s.four,0)
    ) as maxiVal
from
    first f,
    second s
where
    f.id=s.first_id

输出数据
+------+-------+---------+---------+
| id   | title | miniVal | maxiVal |
+------+-------+---------+---------+
|    1 | aaaa  |       3 |       6 |
|    2 | bbbb  |       1 |       4 |
|    3 | cccc  |       1 |       4 |
+------+-------+---------+---------+
3 rows in set (0.00 sec)

运行这个查询使我有点呕吐。像这样编写SQL是多么的错误。

关于php - 在SQL中跳过0和NULL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11392677/

10-12 19:42