Union Query或更好的选择

时间:2013-01-19 19:38:07

标签: php mysql union union-all

我有以下三个表,我想通过userid从中提取数据,这是给他们关系的一个关键字段。我还希望按timestamp按顺序提取数据。下面是表模式的示例,以及我对工作查询不起作用的内容。

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());

1 个答案:

答案 0 :(得分:2)

考虑event_namecommentphoto无关,您不应使用任何类型的UNION。这些表中常见的是user_id。您正在寻找JOIN。像这样:

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'