我正在构建一个社交网络页面,希望在Feed页面上获取所有用户的活动。
我有一张评论表:
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数据,所以我可能不需要太多帮助来组织数组,但我的问题主要是如何从数据库中获取数据。感谢
答案 0 :(得分:1)
最简单的方法可能是使用联合:
SELECT
'comment' AS type,
comment AS content,
FROM comments
UNION
SELECT
'like' AS type,
id_of_liked_item AS item_id
您当然也可以为联盟中的每个查询添加WHERE
条件和其他列,以便用户进行组织。
答案 1 :(得分: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
你可以从那里拿走它。
答案 2 :(得分: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`