通过使用子查询库函数,如何选择与子查询中两个表的条件匹配的记录...?
这是实际的 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');
在这个我怎么能把我的第二个条件...... ???
答案 0 :(得分:2)
顺便说一下,确实需要依赖子查询,这只会增加负载,并且会对类别表中的每一行执行,您可以将等效的连接查询写为
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();