SQL高级语法

SQL高级语法

SQL高级语法:CASE WHEN THEN ELSE END

语法介绍

CASE 开始
WHEN 条件(if[如果前面有when,则后面的when为else if])
ELSE 条件(else)
THEN 赋值(在条件后一定要有的操作)
END 结束

案例

SELECT
    ( CASE WHEN `id` IN ( '3', '4' ) THEN '张三' WHEN `name` LIKE '%子_' THEN '李四' ELSE `name` END ) AS '判断'
FROM
    `name`;

SQL高级语法:UNION ALL

语法介绍

UNION 从两个表中选取所有不同的country(只有不同的值)
UNION ALL 从两个表中选取所有的country(也有重复的值)

案例

SELECT
    country
FROM
    Websites UNION
SELECT
    country
FROM
    appsORDER BY country;

高级案例

SELECT
    stu_id,
    stu_name,
    sum( age )
FROM
    ( SELECT stu_id, stu_name, age FROM stu_info UNION ALL SELECT stu_id, stu_name, age FROM stu_info ) AS t -- 设置派生表
GROUP BY -- 设置分组
    stu_id