MySQL只选择不空值

是否有可能做一个选择语句,只采取非空值?

现在我正在使用这个:

SELECT * FROM table

然后我要用php循环过滤空值。

有没有办法做到:

SELECT * (that are NOT NULL) FROM table

?

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

759786 次浏览

你可以过滤掉特定列中包含NULL值的行:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE somecolumn IS NOT NULL

如果你想过滤掉任何列中包含null的行,那么试试这个:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE col1 IS NOT NULL
AND col2 IS NOT NULL
-- ...
AND coln IS NOT NULL

更新:根据你的评论,也许你想要这个?

SELECT * FROM
(
SELECT col1 AS col FROM yourtable
UNION
SELECT col2 AS col FROM yourtable
UNION
-- ...
UNION
SELECT coln AS col FROM yourtable
) T1
WHERE col IS NOT NULL

我同意Martin的观点,如果你需要这样做,那么你可能应该改变你的数据库设计。

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

SELECT *
FROM table
WHERE YourColumn IS NOT NULL;

为了完整起见,我会提到在MySQL中,你也可以对空安全相等运算符求反,但这不是标准SQL。

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

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

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中测试过。

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*/
Select * from your_table
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;

这种方法的唯一缺点是,你只能比较5列,之后的结果将永远是假的,所以我只比较可以NULL的字段。

我找到了这个解决方案:

此查询为每列选择最后一个非空值。

例子


如果你有一张桌子:

id|title|body
1 |t1   |b1
2 |NULL |b2
3 |t3   |NULL

你会得到:

title|body
t3   |b2

查询


SELECT DISTINCT (


SELECT title
FROM test
WHERE title IS NOT NULL
ORDER BY id DESC
LIMIT 1
) title, (


SELECT body
FROM test
WHERE body IS NOT NULL
ORDER BY id DESC
LIMIT 1
) body
FROM test

希望能帮到你。

我在MySQL中使用\!命令从shell中grep出NULL值:

\! mysql -e "SELECT * FROM table WHERE column = 123456\G" | grep -v NULL

它最好使用适当的.my.cnf,其中指定了数据库/用户名/密码。这样你只需要用\! mysql e| grep -v NULL来包围你的select

SELECT * FROM TABLE_NAME
where COLUMN_NAME <> '';

是的,在你的查询中像下面这样使用NOT NULL

SELECT *
FROM table
WHERE col IS NOT NULL;

以下查询为我工作

当我已经设置列'NULL'的默认值时

select * from table where column IS NOT NULL

当我设置默认值时,什么都没有

select * from table where column <>''

MYSQL IS NOT NULL WITH join AND SELECT, INSERT INTO, DELETE &逻辑运算符,如或,不

Using IS NOT NULL On Join Conditions


SELECT * FROM users
LEFT JOIN posts ON post.user_id = users.id
WHERE user_id IS NOT NULL;


Using IS NOT NULL With AND Logical Operator


SELECT * FROM users
WHERE email_address IS NOT NULL
AND mobile_number IS NOT NULL;


Using IS NOT NULL With OR Logical Operator


SELECT * FROM users
WHERE email_address IS NOT NULL
OR mobile_number IS NOT NULL;
SELECT duration,id FROM `tickets` WHERE duration !=""

哪里的coalesce(所有的列)不是空的