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

现在我正在使用这个:

SELECT * FROM table

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

有没有办法做到:

SELECT * (that are NOT NULL) FROM table

?

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


当前回答

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

其他回答

你可以过滤掉特定列中包含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的观点,如果你需要这样做,那么你可能应该改变你的数据库设计。

我找到了这个解决方案:

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

例子


如果你有一张桌子:

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

希望能帮到你。

以下查询为我工作

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

select * from table where column IS NOT NULL

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

select * from table where column <>''

Mysql不是空的连接和选择,插入,删除和逻辑操作符像或,不是

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 !=""