如何在 ONE 查询中获取一对多关系数据?
示例:一本书有很多作者。
结果返回应该是这样的:
array(
'book_title' => 'HTML for Dummies',
'book_desc' => '...',
'authors' => array(
[0] => array(
'name' => 'Someone',
'dob' => '...'
),
[1] => array(
'name' => 'Someone',
'dob' => '...'
)
)
)
我尝试使用子查询来选择结果但不是运气:
SELECT *, (
SELECT *
FROM authors
WHERE book_id = b.id
) AS authors
FROM book b;
Mysql错误"操作数应包含1列"这意味着我只能选择一列。
您可能会建议我使用加入,但它如何归档返回结果格式,就像我向您展示的那样?
答案 0 :(得分:1)
SELECT
B.id AS book_id, B.name AS book_name,
A.name AS author_name ,A.ID AS author_id
FROM book B
LEFT JOIN
author A ON B.id = A.book_id;
您的输出将是数字数组。
Array
(
[0] => Array
(
[bookId] => 1
[bookName] => Book 1
[authorId] => 1
[authorName] => Author 1
)
[1] => Array
(
[bookId] => 1
[bookName] => Book 1
[authorId] => 2
[authorName] => Author 2
)
[2] => Array
(
[bookId] => 2
[bookName] => Book 2
[authorId] => 3
[authorName] => Author 3
)
[3] => Array
(
[bookId] => 3
[bookName] => Book 3
[authorId] => 4
[authorName] => Author 4
)
)
将此数组转换为多维数组
Array
(
[0] => Array
(
[bookId] => 1
[bookName] => Book 1
[authorName] => Array
(
[0] => Author 1
[1] => Author 2
)
)
[1] => Array
(
[bookId] => 2
[bookName] => Book 2
[authorName] => Array
(
[2] => Author 3
)
)
[2] => Array
(
[bookId] => 3
[bookName] => Book 3
[authorName] => Array
(
[3] => Author 4
)
)
)
答案 1 :(得分:1)
如果您想快速而简单地使用,请使用带有适当分隔符的GROUP_CONCAT
。然后在PHP应用程序(或您正在使用的任何语言)中分割生成的连接字符串字段,以快速获取所需的内部数组。
这样做的好处是输出中每本书只有一行。
答案 2 :(得分:0)
SELECT b.*, a.*
FROM book b
INNER JOIN authors a ON (a.book_id = b.id);
答案 3 :(得分:0)
从mysql中获取数据可能并不容易。 Mysql将以行方式返回。所以书籍或作者都会在结果集中重复。并且你必须相应地解析mysql结果以准备你的数组。
请尝试以下操作:
1)所有以作者为逗号分隔ID的书籍。
"SELECT B.*,group_concat(a.id) as authors
From book b inner join authors as a on b.author_id=a.id
group by b.id;"
2)所有作者都有书的详细信息:
"SELECT A.*,group_concat(B.id) as books
From book B inner join authors as A on B.author_id=A.id
group by A.id;"