是否有可能做一个选择语句,只采取非空值?
现在我正在使用这个:
SELECT * FROM table
然后我要用php循环过滤空值。
有没有办法做到:
SELECT * (that are NOT NULL) FROM table
?
现在当我选择*时,我得到val1,val2,val3,null,val4,val5,null,null等....但我只想得到结果中不为空的值。这可能不使用循环过滤吗?
是否有可能做一个选择语句,只采取非空值?
现在我正在使用这个:
SELECT * FROM table
然后我要用php循环过滤空值。
有没有办法做到:
SELECT * (that are NOT NULL) FROM table
?
现在当我选择*时,我得到val1,val2,val3,null,val4,val5,null,null等....但我只想得到结果中不为空的值。这可能不使用循环过滤吗?
当前回答
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;
其他回答
你应该使用IS NOT NULL。(比较运算符=和<>都在表达式的两侧给出UNKNOWN和NULL。)
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*/
以下查询为我工作
当我已经设置列'NULL'的默认值时
select * from table where column IS NOT NULL
当我设置默认值时,什么都没有
select * from table where column <>''
SELECT duration,id FROM `tickets` WHERE duration !=""
SELECT * FROM TABLE_NAME
where COLUMN_NAME <> '';
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;