从查询中筛选NULL值

时间:2011-09-03 19:06:37

标签: mysql

在下面的查询中,我只希望在风险列

中看到没有NULL值的行
SELECT table1.id, table1.name,
   CASE 
     WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
     WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC

感谢。

上述查询的结果是:

id  name            risk
17  name            very low
17  name            NULL
18  qwert yuiop very low
18  qwert yuiop NULL
19  qwert yuiop very low
19  qwert yuiop NULL
20  qwert yuiop very low
20  qwert yuiop NULL
21  qwert yuiop very low
21  qwert yuiop NULL
22  q           very low
22  q           NULL
23  q           very low
23  q           NULL
24  q           very low
24  q           NULL
25  q           very low
25  q           NULL
26  q           very low
26  q           NULL

我想摆脱NULL。

3 个答案:

答案 0 :(得分:3)

您应该能够使用HAVING子句过滤掉这些行:

SELECT table1.id, table1.name,
   CASE 
     WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
     WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
FROM table1
# Add this row:
HAVING risk IS NOT NULL
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC

答案 1 :(得分:1)

SELECT id, name, risk FROM (
  SELECT table1.id, table1.name,
   CASE 
     WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
     WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
  FROM table1
  ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
) T
WHERE risk IS NOT NULL

更新:我刚刚意识到这是MySQL,而不是一般的SQL问题,所以我不是100%确定MySQL支持这种子查询语法。所以MySQL方法:

  SELECT table1.id, table1.name,
   CASE 
     WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
     WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           AND table2.risk IS NOT NULL
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
  FROM table1
  ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC

所以过滤是在早期完成的,可能会使用索引(尽管优秀的优化器会将第一个Query转移到第二个)。

答案 2 :(得分:0)

SELECT * FROM user where name=""