我正在嘗試在過程中創建select語句。如何從選擇語句中的2個日期獲取最後日期
這裏是我的代碼:
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語句。如何從選擇語句中的2個日期獲取最後日期
這裏是我的代碼:
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(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;
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;
使用情況a.time和b.time。 – Narendra 2012-07-12 09:07:03
您使用的是什麼DBMS? – 2012-07-12 09:31:03