CakePHP - 使用JOIN進行多表聯合查詢

在 SELECT, UPDATE 和 DELETE 語句中可以使用 JOIN 來進行多表聯合查詢,JOIN按照功能分爲以下三類:

  • INNER JOIN (內連接或等值連接):獲取兩個表中字段匹配關係的記錄
  • LEFT JOIN (左連接):獲取左表所有記錄,即使右表沒有對應匹配的記錄
  • RIGHT JOIN (右連接):與 LEFT JOIN 相反,用於獲取右表所有記錄,即使左表沒有對應匹配的記錄

例如有以下三張數據表,它們之間沒有關聯關係,但都有city_code 字段:

  • 城市基礎表 cities
  • 城市信息表 city_infos
  • 城市經濟指標表 city_indicators

現需要從三張數據表中聯合查詢,原始SQL語句如下:

SELECT a.city_name, b.city_population, c.city_gdp
FROM cities a
INNER JOIN city_infos b
ON (
	a.city_code = b.city_code
	AND b.modified_year = '2020'
)
INNER JOIN city_indicators c
ON (
	a.city_code = c.city_code
	AND c.modified_year = '2020'
)
ORDER BY a.city_code ASC

在CakePHP的Controller類中實現以上聯合查詢,方式如下:

$this->Cities->find()
					->select([
						'Cities.city_name', 
						'CityInfos.city_population',
						'CityIndicators.city_gdp'
					])
					->innerJoin(
						[
							'CityInfos' => 'city_infos' //設置表的別名
						],
						[
							'Cities.city_code = CityInfos.city_code',
							'CityInfos.modified_year' => '2020'
						]
					)
					->innerJoin(
						[
							'CityIndicators' => 'city_indicators' //設置表的別名
						],
						[
							'Cities.city_code = CityIndicators.city_code',
							'CityIndicators.modified_year' => '2020'
						]
					)
					->order([
						'Cities.city_code' => 'ASC'
					])
					->map(function($row) { //構建數據格式
						return [
							'city_name' => $row->city_name,
							'city_population' => $row->CityInfos['city_population'],
							'city_gdp' => $row->CityIndicators['city_gdp']
						];
					})
					->toArray();

或者把所有要聯合的表寫在一起:

$this->Cities->find()
					->select([
						'Cities.city_name', 
						'CityInfos.city_population',
						'CityIndicators.city_gdp'
					])
					->join([
						'CityInfos' => [ //設置表的別名
							'table' => 'city_infos',
							'type' => 'INNER',
							'conditions' => [
								'CityInfos.city_code = Cities.city_code',
								'CityInfos.modified_year' => '2020'
							]
						],
						'CityIndicators' => [ //設置表的別名
							'table' => 'city_indicators',
							'type' => 'INNER',
							'conditions' => [
								'CityIndicators.city_code = Cities.city_code',
								'CityIndicators.modified_year' => '2020'
							]
						]
					])
					->order([
						'Cities.city_code' => 'ASC'
					])
					->map(function($row) { //構建數據格式
						return [
							'city_name' => $row->city_name,
							'city_population' => $row->CityInfos['city_population'],
							'city_gdp' => $row->CityIndicators['city_gdp']
						];
					})
					->toArray();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章