1

我正在构建一个社交网络页面,并希望在提要页面上获取所有用户的活动。

我有一个评论表:

user_id    comment                date
1          "Hi...."               24 March 2013
2          "Hello..."             25 March 2013
1          "Another comment..."   26 March 2013

还有一个喜欢表:

user_id    id_of_liked_item     date
1          101                  24 March 2013 
1          145                  25 March 2013

是否可以执行单个查询以将它们放入所有用户活动的数组中,按日期排序?如果是这样,该查询会是什么样子?我的数组需要看起来像这样:

$activity = array(
    array(
        "type"=>"comment",
        "content"=>"Comment goes here"
    ),
    array(
        "type"=>"like",
        "item_id"=>345,
    )
)

我很擅长处理php数据,所以我可能不需要太多帮助来组织数组,但我的问题主要是首先如何从数据库中获取数据。谢谢

4

3 回答 3

1

最简单的方法可能是使用联合:

SELECT
    'comment' AS type,
    comment AS content,
FROM comments
UNION
SELECT
    'like' AS type,
    id_of_liked_item AS item_id

当然,您还可以为WHERE联合中的每个查询添加条件和附加列,以便按用户组织。

于 2013-03-26T15:35:11.280 回答
1

是的,一个 UNION 是要走的路:

SELECT 'comment' AS Type, Comment AS Content, NULL as Item_ID, Date
  FROM Comments
  WHERE User_Id = 1
UNION ALL SELECT 'like', NULL, id_of_liked_item, Date
  FROM Likes
  WHERE User_Id = 1

这将为您提供如下所示的结果集:

Type    Content            Item_ID Date
------- ------------------ ------- -------------
comment Hi....             null    24 March 2013
comment Another comment... null    26 March 2013
like    null               101     24 March 2013
like    null               145     25 March 2013

你可以从那里拿走它。

于 2013-03-26T15:39:34.800 回答
1

尝试使用 UNION:

SELECT * FROM 
(SELECT `user_id`, `comment` AS activity, `date` FROM comments

UNION

SELECT `user_id`, `id_of_liked_item` AS activity, `date` FROM likes) 

AS user_activity

ORDER BY user_activity.`date`
于 2013-03-26T15:43:41.213 回答