MySQL:获取一行和多个相关的行 - 可能吗?

时间:2012-08-10 17:38:32

标签: php mysql database arrays select

假设我有一张表:“汽车”,包含3个字段:ID,品牌,费用。

还有第二个表:“模型”,包含3个字段:id,brand,model_name。

每个“汽车”行可以有多个相关的“模型”行。

是否可以执行sql-select,其输出如下所示?

编辑:我使用PHP进行数据库查询

array(
  [0] => array(
     [id] => 1
     [brand] => mercedes
     [cost] => 1000
     [models] => array(
       [0] => array(
         [id] => 1
         [brand] => mercedes
         [model_name] => slk
       )
       [1] => array(
         [id] => 2
         [brand] => mercedes
         [model_name] => clk
       )
       [2] => array(
         [id] => 3
         [brand] => mercedes
         [model_name] => whatever
       )
     )
  )
)

2 个答案:

答案 0 :(得分:0)

您需要向模型表添加外键关系,例如car_id。然后:

SELECT * FROM cars JOIN models ON car_id = models.id;

这将输出类似于您正在寻找的内容。

假设您正在使用PHP,请使用输出:

$query= "SELECT * FROM cars JOIN models ON car_id = models.id";
$r= @mysqli_query($dbc, $query);
while ($row= mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $carstuff['id']=$row[id];
    $carstuff['brand']=$row[brand];
    $carstuff['cost']=$row[cost];
    $carstuff[$row['models']][]=$row['model_name'];
}

var_dump($carstuff);

请注意,id,品牌和成本会被反复覆盖,但这是可以的,因为它们会被相同的信息覆盖。我不太清楚代码的清洁度,但这是基本的想法。

答案 1 :(得分:0)

试试这个:

<强>查询:

SELECT c.ID, c.brand,c.cost, GROUP_CONCAT(model_name SEPARATOR '","')  as models
, GROUP_CONCAT(m.ID SEPARATOR ',')  as MID
, GROUP_CONCAT(m.brand SEPARATOR '","')  as mbrand
FROM cars c 
LEFT OUTER JOIN model m 
ON m.brand = c.brand
GROUP BY brand;

<强>输出:

ID  BRAND       COST    MODELS            MID   MBRAND
1   audi        1000    m11","m22     4,5   audi","audi
1   mercedes    1200    m1","m2","m3      1,2,3 mercedes","mercedes","mercedes

现在在您的PHP代码中,您可以处理MODEL,MID和MBrand (使用explode

$modelArray = explode(" ,", $row["MODELS");

SQLFIDDLE