0

I have the following three tables and I want to pull data out of them by the userid, that is the one key field that gives them a relationship. I also want to pull the data in order by timestamp Example of the table schema is below and what I have for a union query that is not working.

Table1: userid, event_id, event_name, timestamp
Table2: id_user, comment, timestamp
Table3: user_id, photo, timestamp

 $result5 = mysql_query 
     ("(SELECT event_name, timestamp FROM table1 WHERE userid = '25')
    UNION ALL 
       (SELECT comment,timestamp FROM table2 WHERE id_user = '25')
    UNION ALL 
         (SELECT photo,timestamp FROM table3 WHERE user_id ='25')
    ORDER BY timestamp") 
    or die(mysql_error());
4

1 に答える 1

2

Considering event_name, comment and photo aren't related, you shouldn't be using any sort of UNION. What is common among these tables is the user_id. You're looking for a JOIN. Something like this:

SELECT a.event_name, a.timestamp, b.comment, b.timestamp, c.photo, c.timestamp
FROM table1 a
INNER JOIN table2 b ON b.id_user = a.userid
INNER JOIN table3 c ON c.user_id = a.userid
WHERE a.userid = '25'
于 2013-01-19T19:40:28.163 に答える