我正在尝试在过程中创建选择语句。
这是我的代码:
SELECT u.id, max(a.time), max(b.time)
FROM buy a, sell b, users u
WHERE a.user_id = u.id AND b.user_id = u.id
GROUP BY u.id;
我需要在max(a.time)
和之间取最后一个日期max(b.time)
。
提前致谢
我正在尝试在过程中创建选择语句。
这是我的代码:
SELECT u.id, max(a.time), max(b.time)
FROM buy a, sell b, users u
WHERE a.user_id = u.id AND b.user_id = u.id
GROUP BY u.id;
我需要在max(a.time)
和之间取最后一个日期max(b.time)
。
提前致谢
那这个呢?
SELECT
u.id,
CASE
WHEN max(a.time) > max(b.time) THEN max(a.time)
ELSE max(b.time)
END
FROM buy a, sell b, users u
WHERE a.user_id = u.id AND b.user_id = u.id
GROUP BY u.id;
SELECT u.id, max(case when a.time > b.time then a.time else b.time end)
FROM buy a, sell b, users u
WHERE a.user_id = u.id AND b.user_id = u.id
GROUP BY u.id;
如果你的数据库支持别名查询,试试这个会更有效:
SELECT u.id, case when a_max > b_max then a_max else b_max end
FROM (SELECT u.id, max(a.time) as a_max, max(b.time) as b_max
FROM buy a, sell b, users u
WHERE a.user_id = u.id AND b.user_id = u.id
GROUP BY u.id) x;
如果存在索引,则内部查询可以使用索引来快速获取每列的最大值。
当我们这样做时,让我们使用现代连接语法重新编码:
SELECT u.id, max(case when a.time > b.time then a.time else b.time end)
FROM buy a
JOIN sell b ON b.user_id = u.id
JOIN users u ON a.user_id = u.id
GROUP BY u.id;
SELECT U.ID,
CASE WHEN MAX(A.TIME) > MAX(B.TIME) THEN MAX(A.TIME)
ELSE MAX(B.TIME)
END
FROM BUY A, SELL B, USERS U
WHERE A.USER_ID = U.ID AND B.USER_ID = U.ID
GROUP BY U.ID;