MySQL结合多个表的查询结果

时间:2013-08-24 01:59:01

标签: php mysql sql pdo

假设我有两个表:share和follow。目前,我有一个查询返回按日期排序的最新股票,限制为25个结果。我想做的是查询以下和共享,返回最新的25个结果。但是,我不确定如何做到这一点。

我对股票的查询是这样的:

select s.id, s.name, s.sharer, s.type from shares s where id = :id order by s.date desc limit 0,25

我对粉丝的查询是这样的:

select f.follower, f.following, f.type from followers f where f.following = :id order by f.date desc limit 0,25

如何组合这些,以便如果它从关注者表中选择,它只接受跟随者,跟随和输入,如果它从共享表中选择,它只需要id,name等?这甚至可能吗?

1 个答案:

答案 0 :(得分:3)

认为你正在寻找工会......

    select id, name, sharer, type from (        
    (select s.id as id, 
            s.name as name, 
            s.sharer as sharer, 
            s.type as type, 
            s.date as date 
       from shares s 
       where id = :id order by s.date desc)
        UNION
    (select f.follower as id, 
            f.following as name, 
            f.following as sharer,
            f.type as type,
            f.date as date
        from followers f 
        where f.following = :id order by f.date desc)) 
        order by date desc limit 0,25;

您可能需要根据需要调整别名。