该文章中贴出的sql主要为 mysql 下的语句,部分兼容 sqlserver
查询分组查询每一个分组最新的一条数据
-- 针对没有自增主键ID的查询方式
SELECT
t1.*
FROM
[要查询的表] t1
INNER JOIN ( SELECT [分组字段] , MAX(update_time) AS max_time FROM [要查询的表] GROUP BY [分组字段] ) t2 ON t1.[分组字段] = t2.[分组字段]
AND t1.update_time = t2.max_time
-- 针对有自增主键ID的查询方式
SELECT
t1.*
FROM
[要查询的表] t1
WHERE t1.ID IN ( SELECT MAX(ID) FROM [要查询的表] GROUP BY [分组字段] )
执行一个sql,如果没有查询到结果则执行另一个查询sql
IF EXISTS (
SELECT
name AS person_name
FROM
t_people a
WHERE
a.id = 1)
BEGIN
SELECT
name AS person_name
FROM
t_people a
WHERE
a.id = 1
END
ELSE
BEGIN
SELECT
name AS name
FROM
t_student b
WHERE
b.id = 2
END