JimmyBanks
JimmyBanks

Reputation: 4718

SQL order multiple data rows without combining the rows

For a notification system, I am trying to take multiple rows of completely seperate data, and order them using a unix time stamp. The data from each row is selected by using a users USERID, and then the rows should be ordered from the time they occured.

for example, one of the tables being selected would be:

- USERID   msgid    timestamp
-   3        5       1234567

A final table after selecting all relevant data should look like:

- USERID    msgid    postid    playerpostid     friendrequestid     timestamp  
-   3         5                                                      1234567
-   3                  5                                             1234566
-   3        1234                                                    1234565
-   3                               542                              1234564

As you can see, the tables all combine, but the only thing connecting them is the USERID, and ordered by the timestamp.

Ive tried joins, unfortunately that multiples the results to a ridiculous amount of results.

Upvotes: 0

Views: 120

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65294

SELECT * FROM (
  SELECT 
    USERID, msgid, NULL AS postid, NULL AS playerpostid, NULL AS friendrequestid, timestamp
  FROM messages
  WHERE USERID=3

  UNION ALL

  SELECT 
    USERID, NULL AS msgid, postid, NULL AS playerpostid, NULL AS friendrequestid, timestamp
  FROM posts
  WHERE USERID=3

  UNION ALL

  SELECT 
    USERID, NULL AS msgid, NULL AS postid, playerpostid, NULL AS friendrequestid, timestamp
  FROM playerposts
  WHERE USERID=3

  UNION ALL

  SELECT 
    USERID, NULL AS msgid, NULL AS postid, NULL playerpostid, friendrequestid, timestamp
  FROM friendrequests
  WHERE USERID=3
) AS baseview
ORDER BY timestamp

Upvotes: 4

Related Questions