MySQL查询LEFT OUTER JOIN和IFNULL

时间:2017-11-01 01:36:08

标签: mysql sql join left-join outer-join

我有这个问题:

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

但我希望结果返回所有st表,如果st。st_id存在于at。st_id中,状态列是at表中的内容,如果不是状态是' H',任何人都可以提供帮助吗? this is my table column

4 个答案:

答案 0 :(得分:0)

从不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 :(得分:0)

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

  1. 查询必须全部st st.st_id = at.at_id
  2. 如果st.st_id = at.st_idat.status = status其他status='H'
  3. 我建议的脚本:

    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;

答案 2 :(得分:0)

   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` 

答案 3 :(得分:0)

/ 如果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;