我有4个表链接在一起......
首先是酒店表
然后是城镇表:
然后是区域表:
最后是国家/地区表
我需要做的是按照该镇内有多少家酒店的顺序列出城镇。
我包含区域表和国家/地区表的原因是,在显示该城镇时,我需要显示它所在的国家/地区。这只能通过区域表获得..
因此,使用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>";
}
输出:
这些城市中的每一个都有酒店。我现在需要的只是按每个城镇的酒店订购它们。
任何帮助将不胜感激!感谢。
答案 0 :(得分:4)
$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
答案 1 :(得分:0)
SELECT
hotels.town_id,
count(hotels.hotel_id) from hotels AS hotels_count,
towns.town_name
FROM
hotels,
LEFT JOIN
towns ON hotels.town_id = towns.town_id
GROUP BY hotels.town_id
ORDER BY hotels_count DESC;