PHP从多个表中选择数据

时间:2014-08-20 20:41:02

标签: php mysql sql

我有3张桌子;我需要从“最新活动”Feed中检索数据。 我试图获取如下数据:

$sql = "
SELECT comments.comment_id, comments.comment_time,
   support.ticket_id, support.ticket_date,
   images.image_id, images.image_time
FROM
   comments,
   support,
   images
WHERE
   comments.comment_time >= 1408557172
OR
   support.ticket_date >= 1408557172
OR
   images.image_time >= 1408557172
";

时间是这一天的开始, 但是当我遍历数组时,我得到了很多重复。 我知道我做错了什么但我不知道如何解决它。

1 个答案:

答案 0 :(得分:3)

UNION ALL运算符允许您列出多个表的结果。每个表必须具有相同数量的列,因此我冒昧地为它们添加别名并添加原始列,以便区分它们。

SELECT comment_id as element_id, 
       comment_time as element_time, 
       'comments' as origin
FROM comments
WHERE comments.comment_time >= 1408557172

UNION ALL

SELECT ticket_id as element_id, 
       ticket_date as element_time, 
       'tickets' as origin
FROM support
WHERE support.ticket_date >= 1408557172

UNION ALL

SELECT image_id as element_id, 
       image_time as element_time, 
       'images' as origin
FROM images
WHERE images.image_time >= 1408557172