1

I'm building a social networking page and want to get all the user's activity on a feed page.

I have a comments table:

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

And a likes table:

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

Is it possible to perform a single query to get these into an array of all a user's activity, ordered by date? If so what would that query look lik? My array would need to look something like this:

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

I'm quite good at manipulating php data, so I probably don't need much help organising the array, but my question is mainly how to get the data from the database in the first place. Thanks

1
  • Take a look at SQL JOIN Commented Mar 26, 2013 at 15:34

3 Answers 3

1

Yes, a UNION is the way to go:

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

That will give you a result set that looks like this:

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

And you can take it from there.

Sign up to request clarification or add additional context in comments.

Comments

1

Simplest way would probably be to use a union:

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

You can of course also add WHERE conditions and additional columns to each query in the union for organization by user.

Comments

1

Try using a 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`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.