php - SQL 中跳过 0 和 NULL

标签 php mysql sql

我之前的问题和解决方案:

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

我之前问题中的哪个示例是实现跳过 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) 将 null 转换为 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/

相关文章:

php - 自定义添加到购物车按钮以将多个产品添加到购物车中,数量为 :woocommerce

php - 如何使用 WizTools Rest Client 发送 POST?

PHP 5.6 function_exists 奇怪的行为与 OPCache

php - 使用PHP在Mysql中导入CSV文件,但只导入了236行中的214行

sql - 4 个表内连接 SQL 语句

mysql - Laravel - Eloquent 日志记录更改前后

php - 带条件的 GROUP BY/COUNT 简短查询

MySQL 错误 1093 - 无法在 FROM 子句中指定要更新的目标表

php - 使用用户选择的过滤器选项搜索 MySQL 数据库。数据库结构

sql - 如何将与今天日期最接近的 future 日期设置为默认下拉列表值?