2

我有 2 张桌子。其中一张表包含来自用户的所有邮件,另一张表包含来自用户的所有电话。

Table 1
call_id, | call_date | user_id 
1        |   10/01/12|    3 
2        |   9/01/12 |    3 

Table 2 
mail_id, | mail_date | user_id
1        |   8/01/12 |    3
2            7/01/12 |    3

我需要收到最后 3 个电话和邮件:10/01/12 - 电话 9/01/12 - 电话 8/01/12 - 邮件

4

2 回答 2

2

假设 MySQL,并且只有一个 User_ID ...

SELECT
   *
FROM
(
  SELECT 'call' AS type, id, call_date AS event_date, user_id FROM table_1
  UNION ALL
  SELECT 'mail' AS type, id, mail_date AS event_date, user_id FROM table_2
)
  data
WHERE
  user_id = 3
ORDER BY
  event_date DESC
LIMIT
  3

编辑:糟糕,忘记在 中指定DESCORDER BY抱歉。

于 2012-08-13T15:01:09.503 回答
0
Declare @userID int;
SET @userID=3;

select call_id FROM table_1 
where user_id=@userID
order by call_date desc limit 2

UNION ALL

select mail_id FROM table_2
where user_id=@userID
order by mail_date desc limit 1
于 2012-08-13T15:07:00.560 回答