代码之家  ›  专栏  ›  技术社区  ›  Roy Ryando

MySQL查询左外连接和IFNULL

  •  0
  • Roy Ryando  · 技术社区  · 8 年前

    我有这个问题:

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

    但我希望结果返回所有 st 表,如果 .st_id存在于 at .st_id,status列是 this is my table column

    4 回复  |  直到 8 年前
        1
  •  2
  •   Pankaj_Dwivedi    8 年前

    / /

    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;
    
        2
  •  1
  •   Gordon Linoff    8 年前

    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;
    
        3
  •  0
  •   thecassion    8 年前

    首先,让我试着理解您希望查询做什么:

    1. 查询必须全部 st 哪里 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;

        4
  •  0
  •   Michael B    8 年前
       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` 
    
    推荐文章