我有这些sql表
gouvernorat
id |nom
1 TUNIS
2 ARIANA
3 BEN AROUS
4 MANOUBA
5 NABEUL
delegation
id|id_gouvernorat| nom
1 1 EL MENZAH
2 1 EL HRAIRIA
3 1 EL KABBARIA
22 2 RAOUADE
23 2 SIDI THABET
id\u gouvernorat是gouvernorat的外键
tarifs_zone
zone_a|zone_b|prix
1 2 10
1 3 15
1 4 17
1 5 0
2 3 1
2 4 5
区域a和区域b是委派的外键
我要检索区域a的gouvernorat.nom,delegation.nom,区域b的gouvernorat.nom,delegation.nom和没有重复的价格(a,b没有b,a)
public function Get_zones($start, $length, $order, $dir,$search,$gouvernorat){
$sql='
SELECT (
SELECT delegation.id_gouvernorat
FROM delegation
WHERE tarifs_zones.zone_b=delegation.id)
AS zoneB,
gouvernorat.nom AS gouvernoratA,
gouvernorat.id AS zoneA,
delegation.nom AS delegationA,
tarifs_zones.prix AS prix,
(SELECT gouvernorat.nom
from gouvernorat
WHERE zoneB=gouvernorat.id)
AS gouvernoratB,
(SELECT delegation.nom
FROM delegation
WHERE tarifs_zones.zone_b=delegation.id)
AS delegationB
FROM tarifs_zones
JOIN delegation ON delegation.id = tarifs_zones.zone_a
JOIN gouvernorat ON delegation.id_gouvernorat = gouvernorat.id
HAVING (gouvernoratA= \''.$gouvernorat.'\' OR gouvernoratB= \''.$gouvernorat.'\' OR \'Tous les gouvernorats\'=\''.$gouvernorat.'\')
AND (delegationA LIKE \'%'.$search.'%\' OR gouvernoratA LIKE \'%'.$search.'%\' OR delegationB
LIKE \'%'.$search.'%\' OR gouvernoratB LIKE \'%'.$search.'%\' OR prix LIKE \'%'.$search.'%\')
ORDER BY '.$order.' '.$dir.'
LIMIT '. $start.', '.$length.';
';
return $this->db->query($sql);
}
这是我的功能,但我觉得它太复杂了,我想不出一个方法来更新所有区域的价格取决于两个gouvernorat.nom
1条答案
按热度按时间vuktfyat1#
不需要在后面使用子查询
SELECT
. 你不应该害怕在同一张table上用两次JOIN
s。在这种情况下,您只需要指定别名。因此,您的查询将类似于