gpt4 book ai didi

php - 具有 2 个表和多个条目的 MySQL 查询 JOIN

转载 作者:行者123 更新时间:2023-11-29 06:26:11 24 4
gpt4 key购买 nike

我正在尝试执行 MySQL JOIN 查询以从两个表中获取内容。

这是表 A 的样子:

表A

ID  |  ISBN   |  Type
----------------------
12 | 0338566 | book
15 | 6656565 | post
16 | 9435644 | book
20 | 8525446 | book

和表B

ID  |  tableA_id  |    Key      |  Value
---------------------------------------------
1 | 12 | Author | John Doe
2 | 12 | Title | Book Title 1
3 | 16 | Title | Book Title 2
4 | 20 | Author | John Doe
5 | 20 | Title | Book Title 3

我正在尝试构建我的 SQL 语句来输出所有书籍数据,例如:

ISBN    |    Author    |    Title
-------------------------------------
0338566 | John Doe | Book Title 1
9435644 | | Book Title 2
8525446 | John Doe | Book Title 3

在查找 SQL JOIN 语句后,这就是我想出的:

SELECT tableA.ISBN, tableB.value
FROM tableA, tableB
WHERE tableA.ID = tableB.tableA_id AND tableA.type = “book” AND (tableB.key = "title" OR tableB.author = "store_selector" )

查询仅返回 2 列,因为我只引用了 tableB.value 一次,即使我需要获取其中的两个值(标题和作者)。

我将如何正确构造此查询?

最佳答案

也许不是解决此问题的最佳方法,但我会使用别名两次加入 tableB 并根据需要选择值,如下所示:

SELECT tableA.ISBN, author.value as Author, title.Value as Title
FROM tableA
left join tableB author
on tableA.ID = author.tableA_id
and author.key = "Author"
left join tableB title
on tableA.ID = title.tableA_id
and title.key = "Title"
where tableA.type = “book”

PS:这个数据模型看起来很糟糕,我宁愿更新它并将标题和作者存储在两个不同的表中

关于php - 具有 2 个表和多个条目的 MySQL 查询 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30852313/

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