I have this two tables
comments
| 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 |
views
| 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 |
I would like to get the values from comments.comment
, comments.fullname
, views.user
so I can use them into a foreach and the results will order by date like so:
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
I'm using this query using UNION but I don't think it's the right approach since I can't use the fullname to tell who is writing the comment or the user viewing the file
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
And the result is
| 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 |
So, is there another way to combine this two tables, order them by date and get the rows individually?
Here's the sqlfiddle.