2

假设我有两个表:shares 和 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 等?这甚至可能吗?

4

1 回答 1

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;

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

于 2013-08-24T02:14:44.960 回答