我正在尝试在程序中创建select语句。
这是我的代码:
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)
之间的最后一个日期。
提前致谢
答案 0 :(得分:3)
这个怎么样?
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;
答案 1 :(得分:2)
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;
答案 2 :(得分:0)
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;