MySQL 查询左外连接和 IFNULL

MySQL Query LEFT OUTER JOIN AND IFNULL

我有这个查询:

SELECT st.st_id, st.id, st.name, at.status, at.date
FROM st,at
WHERE st.st_id = at.at_id;

但我想要结果 return 所有 st table,如果 st.st_id 存在于 at.st_id,status栏是attable里面的什么,如果不是status是'H',谁能帮帮忙? this is my table column

从不FROM 子句中使用逗号。 始终 使用正确、明确的 JOIN 语法。那么写查询会更容易:

SELECT st.st_id, st.id, st.name, COALESCE(at.status, 'H') as status, at.date
FROM st LEFT JOIN
     at
     ON st.st_id = at.at_id;

首先让我尝试了解您希望查询执行的操作:

  1. 查询必须全部st where st.st_id = at.at_id
  2. 如果st.st_id = at.st_id那么at.status = status否则status='H'

我推荐的脚本:

SELECT st.st_id, st.id, st.name, IF(st.st_id = at.st_id, at.status, 'H') AS status, at.date FROM st LEFT JOIN at ON st.st_id = at.at_id;

   SELECT   st.st_id,
            st.id,
            st.name,
            st.cl_id,
            st.gender,
            CASE WHEN ISNULL(at.st_id ) THEN 'H' ELSE at.status
   FROM `st`
   LEFT JOIN `at` ON `st`.`st_id` = `at`.`st_id` 

/如果 DB 为 MYSQL/

,则使用 IFNULL
SELECT st.st_id, st.id, st.name, IFNULL(at.status,'H') as status, at.date
FROM st LEFT JOIN
     at
     ON st.st_id = at.at_id;