我有 4 个链接在一起的表...
首先是酒店表
- 酒店编号
- town_id
- 酒店名称
然后是towns表:
- town_id
- 地区编号
- 镇名
然后是regions表:
- 地区编号
- country_id
- 地区名称
最后是国家表
- country_id
- 国家名称
我需要做的是按照该镇内有多少家酒店的顺序列出这些镇。
我包含区域表和国家/地区表的原因是,在显示那个城镇时,我需要显示它来自的国家/地区。这只能通过地区表获得..
因此,使用 CodeIgniter 中的事件记录,到目前为止我已经这样做了:
$this->db->join('regions','towns.town_region_id = regions.region_id');
$this->db->join('countries','regions.region_country_id = countries.country_id');
$query = $this->db->get('towns');
foreach ($query->result() as $row) {
echo "<li>";
echo "$row->town_name, $row->country_name";
echo "</li>";
}
这个输出:
- 英国伦敦
- 美国华盛顿
- 美国纽约
- 俄罗斯莫斯科
- 等等等等
这些城市中的每一个都有酒店。我现在需要做的就是根据每个城镇的旅馆数量来排序。
任何帮助将不胜感激!谢谢。
最佳答案
$this->db->select('t.*,c.*,COUNT(h.hotel_id) AS nhotels');
$this->db->from('towns t');
$this->db->join('hotels h','h.town_id = t.town_id');
$this->db->join('regions r','t.town_region_id = r.region_id');
$this->db->join('countries c','r.region_country_id = c.country_id');
$this->db->group_by('t.town_id');
$this->db->order_by("nhotels",'DESC');
$query = $this->db->get();
这将产生以下查询:
SELECT `t`.*, `c`.*, COUNT(h.hotel_id) AS nhotels
FROM (`towns` t)
JOIN `hotels` h
ON `h`.`town_id` = `t`.`town_id`
JOIN `regions` r
ON `t`.`town_region_id` = `r`.`region_id`
JOIN `countries` c
ON `r`.`region_country_id` = `c`.`country_id`
GROUP BY `t`.`town_id`
ORDER BY `nhotels` DESC
关于php - CodeIgniter,按单独连接表中的行数排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889053/