Php MySQL join,以数组或列表的形式从一个表返回一行,从另一个表返回多行
我正在做一个为笔记本电脑编目的项目,因此我正在尽可能多地重复使用信息。MySQL表的简化版本包括:Php MySQL join,以数组或列表的形式从一个表返回一行,从另一个表返回多行,php,mysql,join,Php,Mysql,Join,我正在做一个为笔记本电脑编目的项目,因此我正在尽可能多地重复使用信息。MySQL表的简化版本包括: Table: laptop |----------------------------------| | id | make | line | model | | 1 | 1 | 1 | Late 2015 13" | |----------------------------------| Table: make |----------------------
Table: laptop
|----------------------------------|
| id | make | line | model |
| 1 | 1 | 1 | Late 2015 13" |
|----------------------------------|
Table: make
|----------------------------------|
| id | name | other info |
| 1 | Apple | |
|----------------------------------|
Table: line
|----------------------------------|
| id | name | other info |
| 1 | MacBook Pro | |
|----------------------------------|
Table: networking
|----------------------------------|
| id | name | other info |
| 1 | A wifi card | |
| 2 | Another card | |
| 3 | Yet another | |
|----------------------------------|
Table: laptop_networking
|----------------------------------|
| id | networking | laptop |
| 1 | 3 | 1 |
| 2 | 1 | 1 |
|----------------------------------|
到目前为止,我使用current语句在PHP中检索数据
$statement = $dbc->prepare("
SELECT l.id
, m.id AS makeID
, m.name AS makeName
, n.id AS lineID
, n.name AS lineName
, l.model
FROM laptop l
JOIN make m
ON l.make = m.id
JOIN line n
ON l.line = n.id
WHERE l.id = :laptop);
$statement->bindParam(':laptop', $anID, PDO::PARAM_INT);
$statement->execute();
$theLaptop = $statement0>fetch();
目前,使用$anID=1运行此代码会返回
|---------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | Model |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" |
|---------------------------------------------------------------|
我想做的是在表中附加另一列,它返回所有来自网络的名称,这些名称的ID等于laptop_Networking中的一行,其中laptop字段等于检索到的laptop行的ID
例如:
|------------------------------------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | model | networking |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" | Yet another, A wifi card |
|------------------------------------------------------------------------------------------|
这是可能的,因为我多次尝试不同类型的联接都没有得到预期的结果
谢谢尝试以下查询:
SELECT laptop.id,
make.id AS makeID,
make.name AS makeName,
line.id AS lineID,
line.name AS lineName,
laptop.model,
t.networking
FROM laptop
INNER JOIN make
ON laptop.make = make.id
INNER JOIN line
ON laptop.line = line.id
INNER JOIN
(
SELECT t1.laptop, GROUP_CONCAT(t2.name) AS networking
FROM laptop_networking t1
INNER JOIN networking t2
ON t1.networking = t2.id
GROUP BY t1.laptop
) t
ON laptop.id = t.laptop
WHERE laptop.id = :laptop
此处演示:
更合适谢谢,我刚刚将上面列出的内部联接添加到完整代码中,并在第一次测试中收到了所需的结果。查询字符串没有右引号