gpt4 book ai didi

一个查询中的 MySQL 一对多关系

转载 作者:行者123 更新时间:2023-11-29 05:12:14 25 4
gpt4 key购买 nike

如何在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错误“Operand should contain 1 column(s)”这意味着我只能选择一列。

您可能会建议我使用 join,但它如何像我向您展示的那样归档返回结果格式?

最佳答案

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;

Refer : http://sqlfiddle.com/#!9/633cfa1/2

您的输出将在数字数组中。

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
)

)

)

Refer : https://3v4l.org/q1dli

关于一个查询中的 MySQL 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com