MySQL SELECT 仅非空值

MySQL SELECT only not null values(MySQL SELECT 仅非空值)
本文介绍了MySQL SELECT 仅非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行只接受 NOT NULL 值的 select 语句?

Is it possible to do a select statement that takes only NOT NULL values?

现在我正在使用这个:

SELECT * FROM table

然后我必须用 php 循环过滤掉空值.

And then I have to filter out the null values with a php loop.

有没有办法:

SELECT * (that are NOT NULL) FROM table

?

现在当我选择 * 我得到 val1,val2,val3,null,val4,val5,null,null 等...但我只想得到结果中不为空的值.不用循环过滤可以吗?

Right now when I select * I get val1,val2,val3,null,val4,val5,null,null etc.... but I just want to get the values that are not null in my result. Is this possible without filtering with a loop?

推荐答案

你应该使用 IS NOT NULL.(比较运算符 =<> 都给出 UNKNOWNNULL 在表达式的两侧.)

You should use IS NOT NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

为了完整起见,我会提到在 MySQL 中你也可以否定 null 安全相等运算符 但这不是标准 SQL.

Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.

SELECT *
FROM table 
WHERE NOT (YourColumn <=> NULL);

已编辑以反映评论.听起来您的表格可能不是第一范式,在这种情况下,更改结构可能会使您的任务更容易.不过,还有其他几种方法...

Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...

SELECT val1 AS val
FROM  your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2 
FROM  your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/

上面的缺点是它对每一列多次扫描表一次.下面可能可以避免这种情况,但我还没有在 MySQL 中测试过.

The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.

SELECT CASE idx
         WHEN 1 THEN val1
         WHEN 2 THEN val2
       END AS val
FROM   your_table
        /*CROSS JOIN*/
       JOIN (SELECT 1 AS idx
                   UNION ALL
                   SELECT 2) t
HAVING val IS NOT NULL  /*Can reference alias in Having in MySQL*/

这篇关于MySQL SELECT 仅非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)