Select 与另一个 table 没有关系时的值

Select value when no relationship from another table

我有 2 个表,其中 1 列应该有一个外键,但不幸的是没有应用 FK 约束,插入的值变得不一致

table1
--------
id    name    consultant
1    mike         1
2    allan        2
3    jenny        0
4    dan         -1
5    kevin        patrick
6    Sarah        


consultant
----------
id     name
1      steve
2      james
3      craig

我试过了

SELECT
    table1.id AS id,
    table1.name AS name,
    CASE
        WHEN table1.consultant = '0' OR table1.consultant = '' THEN 'For allocation'
        WHEN table1.consultant = '-1' THEN 'Do not allocate'
        WHEN consultant.id NOT EXISTS THEN CONCAT('Cant find:',table1.consultant)
    END AS consultant_name
FROM
    table1
        LEFT JOIN consultant ON table1.consultant = consultant.id

我需要得到

的结果
id    name     consultant_name
1     mike     steve
2     allan    james
3     jenny    'For allocation'
4     dan      'Do not allocate'
5     kevin    'Cant find:patrick'
6     Sarah    'For allocation'

问题:

  1. case 的第一个条件中添加针对 IS NULL 的检查。
  2. case的第三个条件中使用ISNULL代替NOT EXISTS
  3. case 使用 ELSE 部分。否则前 2 条记录将 return NULL

解法:

SELECT
    table1.id AS id,
    table1.name AS name,
    CASE
        WHEN table1.consultant = '0' OR table1.consultant = '' OR table1.consultant IS NULL THEN 'For allocation'
        WHEN table1.consultant = '-1' THEN 'Do not allocate'
        WHEN consultant.id IS NULL THEN CONCAT('Cant find:',table1.consultant)
        ELSE consultant.name
    END AS consultant_name
FROM
    table1
        LEFT JOIN consultant ON table1.consultant = consultant.id

结果:

id  name    consultant_name
------------------------------
1   mike    steve
2   allan   james
3   jenny   For allocation
4   dan     Do not allocate
5   kevin   Cant find:patrick
6   Sarah   For allocation

示例结果 SQL Fiddle

我认为您需要这样的查询:

SELECT
    table1.id AS id,
    table1.name AS name,
    CASE
        WHEN table1.consultant = '0' OR table1.consultant = '' THEN 'For allocation'
        WHEN table1.consultant = '-1' THEN 'Do not allocate'
        WHEN consultant.id is null  THEN CONCAT('Cant find:',table1.consultant)
        ELSE consultant.name
    END AS consultant_name
FROM
    table1
        LEFT JOIN consultant ON table1.consultant = CAST(consultant.id AS varchar(max));