php - CodeIgniter,按单独连接表中的行数排序?

标签 php mysql codeigniter

我有 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/

相关文章:

php - 获取 mysql 行,除非它是重复的,在这种情况下忽略它

php - shuffle() 不能按预期使用关联数组

php - 连接两个表获取出勤和用户名mysql

mysql - 如何获取为Null的表的列名?

php - 如何从 Mysql 中获取 json 数据并将其转换为 CodeIgniter 中的数组

javascript - 如何使用javascript对json类型数据进行排序?

php - 检查字符串是否包含 PHP 中不允许的 SQL 命令

php - 自动完成菜单中的单独网址

mysql - 我可以在不区分大小写的文件系统上强制 MySql 表名区分大小写吗

java - Hibernate中的ObjectNotFoundException : No row with the given identifier exists