【问题标题】:How to convert sql union to codeigniter way如何将 sql union 转换为 codeigniter 方式
【发布时间】:2020-01-10 07:23:01
【问题描述】:

如何使用 PHP CodeIgniter 框架进行 UNION 查询我在执行此查询时遇到错误

Every derived table must have its own alias

型号

function search_blog($title){
$query = $this->db->query("SELECT * FROM (
                SELECT id,section,title,img,year,lastupdateon AS ondate,'moves' AS dept,STATUS FROM movies
                UNION
                SELECT ID,section,Title,img,year,lastupdateon AS ondate,'kid' AS dept,STATUS FROM kids
                UNION
                SELECT ID,views,Title,img,version AS year,ondate,'software' AS dept,STATUS FROM soft
                UNION
                SELECT ID,section,Title,img,'PC Game' AS year,ondate,'game' AS dept,STATUS FROM games
                UNION
                SELECT ID,season,Title,img,type AS year,lastupdatedon AS ondate,'tvshow' AS dept,STATUS FROM tvshows
                )");
        $this->db->like('Title', $title , 'after');
        $this->db->order_by('ondate', 'DESC');
        $this->db->limit(10);
        return $this->db->get($query)->result();
    }

如何修改

【问题讨论】:

    标签: php sql codeigniter search union


    【解决方案1】:

    你可以简单地通过为每个表添加查询并使用这样的联合来连接它们

    $this->db->select('ID,section,title,img,year,lastupdateon AS ondate,`moves` AS dept,STATUS');
    $this->db->from('movies');
    $query1 = $this->db->get_compiled_select();
    
    $this->db->select('ID,section,title,img,year,lastupdateon AS ondate,`kid` AS dept,STATUS');
    $this->db->from('kids');
    $query2 = $this->db->get_compiled_select();
    
    $this->db->select('ID,views,title,img,version AS year,ondate,`software` AS dept,STATUS');
    $this->db->from('soft');
    $query3 = $this->db->get_compiled_select();
    
    
    $this->db->select('ID,section,title,img,'PC Game' AS year,ondate,`game` AS dept,STATUS');
    $this->db->from('games');
    $query4 = $this->db->get_compiled_select();
    
    $this->db->select('ID,season,title,img,type AS year,lastupdatedon AS ondate,`tvshow` AS dept,STATUS');
    $this->db->from('tvshows');
    $query5 = $this->db->get_compiled_select();
    
    $this->db->like('title', $title , 'after');
    $this->db->order_by('ondate', 'DESC');
    $this->db->limit(10);
    
    
    $query = $this->db->query($query1 . ' UNION ' . $query2. ' UNION ' . $query3. ' UNION ' . $query4. ' UNION ' . $query5);
    
    return $this->db->get($query)->result();
    

    【讨论】:

    • 评论不用于扩展讨论;这个对话是moved to chat
    • 请看一下。我认为它是固定的
    • 它从上次发布日期而不是从搜索词中获取结果
    • 现在完美运行,谢谢
    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多