【问题标题】:subquery where condition from different table in codeigniter子查询 where 来自 codeigniter 中不同表的条件
【发布时间】:2014-09-23 06:30:52
【问题描述】:

通过使用子查询库函数,如何从子查询中的两个表中选择符合条件的记录...?

这是实际的sql查询

SELECT *, (SELECT count('report_id') 
           FROM report 
           WHERE report.category = category.cat_id 
                 and report.user_id IN (68, 69, 70)) AS cnt 
FROM (`category`)

我需要 codeigniter 中的等价物:

    $this->db->select('*')->from('category');
    $sub = $this->subquery->start_subquery('select');
    $sub->select("count('report_id')")->from('report')
        ->where_in(array('user_id'=>(68, 69, 70)));
    $this->subquery->end_subquery('number'); 

在这我怎么能把我的第二个条件...???

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    顺便说一句,是否真的需要依赖子查询,这只会增加负载,它将对类别表中的每一行执行,您可以将等效连接查询编写为

    SELECT c.*, 
    COUNT(DISTINCT r.report_id) AS cnt /*you can omit distinct if you have unique report ids  */
    FROM `category` c
    LEFT JOIN report r ON r.category = c.cat_id AND r.user_id IN (68, 69, 70)
    GROUP BY c.cat_id
    

    和活动记录查询一样

    $result = $this->db->select('c.*,COUNT(DISTINCT r.report_id) AS cnt ',FALSE)
        ->from('category c')
        ->join('report r','r.category = c.cat_id AND r.user_id IN (68, 69, 70)','LEFT')
        ->group_by('c.cat_id')
        ->get()
        ->result();
    

    【讨论】:

    • 感谢它的作品,,但是如果出现这种情况,我怎样才能将第二个表格字段放在 where 条件中
    • @rbvishnu 您可以使用->where('r.column_name',$value) 来应用 ny 过滤器,这是您要求的吗?
    • 我需要包含这个条件:report.category = category.cat_id
    • 对不起,我想要的是在使用库的子查询方法中包含 where 条件。这怎么可能......如果我更喜欢第一种方法,无论如何我都会使用你提到的 join 得到结果
    • @rbvishnu which subquery library 您正在使用 CI 吗?另外我不知道在活动记录中使用子查询,并且连接在性能上比子查询更好
    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多