codeigniter 如何在CI 3.x中实现SQL子查询?

baubqpgj  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个SQL查询如下:

SELECT a.name_prov AS prov,city,a.cases 
FROM 
    (SELECT c.name_prov,b.city,a.cases, 
    ROW_NUMBER() OVER (PARTITION BY c.name_prov ORDER BY CAST(a.cases AS INT)DESC) AS rn 
    FROM tb_cases a  
    JOIN tb_city b ON a.id_city = b.id_city 
    JOIN tb_prov c ON a.id_prov = c.id_prov 
    ORDER BY c.name_prov 
    ) a 
ORDER BY a.name_prov,rn

如何在CodeIgniter 3.x版活动记录中编写上述select语句?

r1zk6ea1

r1zk6ea11#

我建议你去CodeIgniter论坛看看这类问题。

$subQuery = $this->db->select()
->....
->get_compiled_select();

$this->db->select('*')
->from("($subQuery) as t", false);

来源:https://forum.codeigniter.com/showthread.php?tid=70943
此外,对于您提供的查询,不需要子查询:

SELECT c.name_prov as prov, b.city, a.cases, ROW_NUMBER() OVER (PARTITION BY c.name_prov ORDER BY CAST(a.cases AS INT) DESC) AS rn 
FROM tb_cases a  
JOIN tb_city b ON a.id_city = b.id_city 
JOIN tb_prov c ON a.id_prov = c.id_prov
ORDER BY prov, rn

这应该相当于您查询。

相关问题