是否可以执行仅采用NOT NULL值的select语句?
现在我正在使用它:
SELECT * FROM table
然后我必须用php循环过滤掉空值。
有办法吗?
SELECT * (that are NOT NULL) FROM table
现在当我选择*我得到val1,val2,val3,null,val4,val5,null,null等....但我只想获得结果中不为null的值。如果没有使用循环过滤,这是否可行?
答案 0 :(得分:409)
您应该使用IS NOT NULL
。 (比较运算符=
和<>
都会在表达式的任一侧为UNKNOWN
提供NULL
。)
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
为了完整起见,我会在MySQL中提到你也可以否定null safe equality operator,但这不是标准的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*/
答案 1 :(得分:17)
您可以过滤掉特定列中包含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说,如果你需要这样做,那么你应该改变你的数据库设计。
答案 2 :(得分:12)
Select * from your_table
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;
这种方法的唯一缺点是你只能比较5列,之后结果总是假的,所以我只比较可以NULL
的字段。
答案 3 :(得分:7)
我找到了这个解决方案:
此查询为每列选择最后一个非空值。
实施例
如果你有一张桌子:
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
我希望能帮助你。
答案 4 :(得分:2)
我在MySQL中使用\!
命令从shell中删除NULL值:
\! mysql -e "SELECT * FROM table WHERE column = 123456\G" | grep -v NULL
最适合使用指定数据库/用户名/密码的.my.cnf
。这样,您只需使用select
和\! mysql e
包围| grep -v NULL
。
答案 5 :(得分:1)
以下查询对我有用
当我将列的默认值设置为“ NULL”时
select * from table where column IS NOT NULL
当我将默认值设置为空时
select * from table where column <>''
答案 6 :(得分:0)
是,请在您的查询中使用NOT NULL
,如下所示。
SELECT *
FROM table
WHERE col IS NOT NULL;
答案 7 :(得分:0)
MYSQL IS NOT NULL WITH JOINS AND SELECT, INSERT INTO, DELETE & LOGICAL OPERATOR LIKE OR , NOT
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;
答案 8 :(得分:-2)
SELECT duration,id FROM `tickets` WHERE duration !=""
答案 9 :(得分:-4)
SELECT * FROM TABLE_NAME
where COLUMN_NAME <> '';