SQL中为NULL的情况

时间:2014-11-23 17:27:05

标签: mysql sql select null

我有这段代码,但它没有用。

当NULL存在时,它应该''out而没有标题,但它没有。

SELECT employee.pin,
CASE gender
WHEN 'M' or (employee.titel IS NULL) THEN CONCAT('Mister ', ' ', ' ', person.fname, ', ' )
WHEN 'W' or (employee.titel IS NULL) THEN CONCAT('Mrs ', ' ', ' ',     person.fname, ', ' )
WHEN 'M' THEN CONCAT('Mister ', employee.titel, ' ', person.fname, ', ' )
WHEN 'W' THEN CONCAT('Mrs ', employee.titel, ' ', person.fname, ', ' )
END AS salutation
FROM person,employee

where person.pin=employee.pin
ORDER BY pin

2 个答案:

答案 0 :(得分:2)

您可以使用仅跳过空值的CONCAT_WS:

SELECT
  employee.pin,
  CASE WHEN gender='M' THEN CONCAT_WS(' ', 'Mister', employee.titel, person.fname)
       WHEN gender='W' THEN CONCAT_WS(' ', 'Mrs', employee.titel, person.fname)
  END AS salutation
FROM
  person INNER JOIN employee
  ON person.pin=employee.pin
ORDER BY pin

答案 1 :(得分:1)

您必须使用其他CASE语法,因为NULL不等于任何内容:

CASE
WHEN gender='M' or (employee.titel IS NULL) THEN CONCAT('Mister ', ' ', ' ', person.fname, ', ' )
WHEN gender='W' or (employee.titel IS NULL) THEN CONCAT('Mrs ', ' ', ' ',     person.fname, ', ' )
WHEN gender='M' THEN CONCAT('Mister ', employee.titel, ' ', person.fname, ', ' )
WHEN gender='W' THEN CONCAT('Mrs ', employee.titel, ' ', person.fname, ', ' )
WHEN gender IS NULL THEN ...
END AS salutation