运行2个SQL select语句

时间:2016-11-30 15:57:52

标签: php union-all

我正在尝试运行2个SQL Select查询以从2个不同的表中检索数据,然后回显两个表中的字段。我正在尝试的代码似乎没有用,任何帮助都会受到赞赏。

$ModelID = $_GET['model_id'];

$result = mysqli_query($con, "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$ModelID'

UNION ALL

SELECT CarModel, CarMake, CostPerDay FROM Model WHERE ModelID = '$ModelID'");   

while($row = $result->fetch_assoc())    
{     
    echo $row["CarModel"];
    echo $row["CarMake"];
    echo $row["CostPerDay"];    
    echo $row["RegNumber"];        
    echo " - " .$row["Colour"];         
}                       

2 个答案:

答案 0 :(得分:1)

您可以更改请求:

SELECT c.RegNumber, c.Colour , m.CarModel, m.CarMake, m.CostPerDay FROM Car c INNER JOIN Model m ON m.ModelID=c.ModelID WHERE c.ModelID = '$ModelID'

答案 1 :(得分:1)

尝试LEFT JOIN

$result = mysqli_query($con, 
   "SELECT c.RegNumber, c.Colour, m.CarModel, m.CarMake, m.CostPerDay 
   FROM Car AS c
   LEFT JOIN Model as m ON c.ModelID = m.ModelID 
   WHERE c.ModelID = '".$ModelID."'"
);