使用Union替代方案从两个表中按日期排序

时间:2014-03-13 15:32:03

标签: mysql sql union

我有这两张桌子

评论

| ID | COMMENT | FULLNAME       | PHOTO_ID |           CREATED_AT            |
|----|---------|----------------|----------|---------------------------------|
| 76 | comment1| John Smith     |       14 | February, 25 2014 10:38:02+0000 |
| 77 | comment2| James Anderson |       14 | February, 25 2014 10:38:14+0000 | 
| 78 | comment3| Will Smith     |       15 |    March, 11 2014 14:24:08+0000 |

视图

| ID | USER | PID |           CREATED_AT            |
|----|------------|---------------------------------|
| 63 | user1| 15  | February, 25 2014 11:12:03+0000 |
| 64 | user1| 14  | February, 25 2014 11:14:10+0000 | 
| 66 | user2| 15  | February, 25 2014 11:15:16+0000 |
| 68 | user2| 14  | February, 25 2014 10:38:12+0000 |

我想从comments.commentcomments.fullnameviews.user获取值,以便我可以将它们用于foreach,结果将按日期顺序排列:

John Smith added a comment February, 25 2014 10:38:12 //comment1 user2 viewed the file February, 25 2014 10:38:12 //view James Anderson added a comment February, 25 2014 10:38:12 //comment2

我正在使用UNION使用此查询,但我不认为这是正确的方法,因为我无法使用全名来判断谁在撰写评论或查看文件的用户

SELECT comment, fullname, comments.created_at
FROM comments
WHERE comments.photo_id = 14
UNION
SELECT user, '', views.created_at
FROM views
WHERE views.pid = 14
ORDER BY created_at DESC

结果是

|  COMMENT |       FULLNAME |                      CREATED_AT |
|----------|----------------|---------------------------------|
|    user1 |                | February, 25 2014 11:14:10+0000 |
| comment2 | James Anderson | February, 25 2014 10:38:14+0000 |
|    user2 |                | February, 25 2014 10:38:12+0000 |
| comment1 |     John Smith | February, 25 2014 10:38:02+0000 |

那么,是否有另一种方法来组合这两个表,按日期排序并单独获取行? 这是sqlfiddle

2 个答案:

答案 0 :(得分:0)

不是100%确定这是否是您正在寻找的,但您可以尝试一下......

SELECT IF(comment = 'view', 'view', 'comment') AS type, comment, fullname, created_at
FROM
(
  SELECT comment, fullname, comments.created_at
  FROM comments
  WHERE comments.photo_id = 14
  UNION
  SELECT 'view', user, views.created_at
  FROM views
  WHERE views.pid = 14
) tbl
ORDER BY created_at DESC

sqlfiddle

答案 1 :(得分:0)

这应该可以解决问题:

SELECT
    USER, ACTION, TIME
FROM
    (
    SELECT
         FULLNAME as USER
        ,'COMMENT' as ACTION
        ,CREATED_AT as TIME
    FROM comments
    )
    UNION ALL
    (
    SELECT
         USER as USER
        ,'VIEW' as ACTION
        ,CREATED_AT as TIME
    FROM views
    )
WHERE
    VIEWS_PID = 14
OERDER BY
    TIME DESC