从一个表中选择匹配值到另一个表中的多个值

时间:2018-02-06 03:18:30

标签: php mysql subquery inner-join

    cars                 models
car_id  car       car_id   model_id  model
   1    ford         1         1      mustang
   2    fiat         1         2      focus
   3    toyota       1         3      escort
                     2         4      500
                     2         5      spider
                     3         6      tacoma

我所拥有的两个表格要复杂得多,所以我从另一个用户问题中获取了这个代码,这几乎是我想要的,但我不知道如何正确地使用PHP格式化输出

SELECT c.Car, m.Model_id, m.Model
FROM models m
INNER JOIN car c ON c.Car_id = m.Car_id
WHERE m.Car_id = (SELECT Car_id FROM models WHERE Model = 'Escort');

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {

$model = $row['Model'];
$vehicle = $row['Car'];

    ford mustang
    ford focus
    ford escort

我想要的是

    ford
        mustang
        focus
        escort

我已经在下面发布了我的更新后的尝试,但是我打赌你很好,人们可以让它变得更漂亮。

$sql = "
SELECT c.Car, m.Model_id, m.Model 
FROM models m 
INNER JOIN car c   
ON     c.Car_id = m.Car_id
WHERE m.Car_id = '1' ";

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$vehicle[$row['Car']][] = $row['Model'];
}

echo "<table>";
foreach( $vehicle as $value => $key )
{echo '<tr><td>'.$value.'</td></tr>'; 
foreach( $key as $mod) 
{echo '<tr><td>'.$mod.'</td></tr>';}}

}

结果:
福特
野马
重点
护送

2 个答案:

答案 0 :(得分:1)

您可能想要一个带钥匙的数组作为车型。循环你是结果并根据需要附加到数组。

例如:

vehicle=[];
while($row = mysqli_fetch_assoc($result)) {
    if (!array_key_exists($row['Car'], $vehicle)){
        $vehicle[$row['Car']] = [];
    }
    $vehicle[$row['Car']][] = $row['Model'];
}

输出将如下所示:

array(1) {
  ["Ford"]=>
  array(2) {
    [0]=>
    string(4) "focus",
    [1]=>
    string(6) "escort"
  }
}

答案 1 :(得分:0)

heroku