如何在codeigniter中显示4个表中的最新项目

时间:2016-08-01 13:42:05

标签: php codeigniter

我在我的主页上创建了一个div来显示我数据库中四个表的最新项目,但是我遇到了查询结构的问题,我为模型尝试了这个:

   $sql = "(SELECT name,type, screenshot,url from music WHERE status = 1   ) 
    UNION ALL (SELECT name,type, screenshot,url from lyrics WHERE status = 1   )
    UNION ALL(SELECT name,type, screenshot,url from mixtapes WHERE status = 1  ) 
    UNION ALL (SELECT name,type, screenshot, vurl from videos WHERE  status = 1  ) ORDER BY 'date_added' desc LIMIT 8";
     $query = $this->db->query($sql);
     return $query->result();  

此查询仅从音乐表中检索,并且limit关键字仅适用于从音乐表中检索的项目,但我希望查询作为一个查询运行,以便根据来自的最新项目检索项目四个表和limit关键字将结果限制为八个项目,请问我如何构建查询,还是有其他方法可以做到这一点?请帮忙..

2 个答案:

答案 0 :(得分:0)

最简单的方法:

$sql = "
    SELECT * FROM
    (
        SELECT name,type, screenshot,url from music WHERE status = 1
        UNION ALL
        SELECT name,type, screenshot,url from lyrics WHERE status = 1
        UNION ALL
        SELECT name,type, screenshot,url from mixtapes WHERE status = 1
        UNION ALL
        SELECT name,type, screenshot, vurl from videos WHERE  status = 1
    ) t
    ORDER BY 'date_added' desc
    LIMIT 8
";
$query = $this->db->query($sql);
return $query->result();  

答案 1 :(得分:0)

如果你想要每个列表中最近的两个项目;你可以使用这样的东西:

(SELECT name,type, screenshot,url from music 
    WHERE status = 1 order by date_added desc limit 0,2) 
UNION
(SELECT name,type, screenshot,url from lyrics  
    WHERE status = 1 order by date_added desc limit 0,2)
UNION
(SELECT name,type, screenshot,url from mixtapes 
    WHERE status = 1 order by date_added desc limit 0,2) 
UNION
(SELECT name,type, screenshot,url from videos 
    WHERE status = 1 order by date_added desc limit 0,2) 

或者,如果您想要所有4个表中最近的8个项目:

SELECT * FROM (
    (SELECT name,type, screenshot,url from music WHERE status = 1) 
    UNION
    (SELECT name,type, screenshot,url from lyrics WHERE status = 1) 
    UNION
    (SELECT name,type, screenshot,url from mixtapes WHERE status = 1) 
    UNION
    (SELECT name,type, screenshot,url from videos WHERE status = 1) 
) ORDER BY date_added DESC LIMIT 0,8;