gpt4 book ai didi

mysql - 从相关表中选择匹配的属性对

转载 作者:行者123 更新时间:2023-11-30 00:47:26 25 4
gpt4 key购买 nike

我有两张表,一张是书籍,另一张是版本。每个版本在“edtype”列中都有一个属性,例如“精装本”或“平装本”。每个图书行可以有多个相关的版本行。

select books.id, books.name, editions.id, editions.edtype from books
join editions on books.id=editions.bookid;

会返回如下内容:

1  name1  1  hardback
1 name1 2 paperback
2 name2 3 paperback
3 name3 4 hardback

我想要做的是找到具有 (1) 精装和平装版本的书籍:

1  name1

(2) 平装本,但不是精装本

2  name2

(3) 精装本而非平装本

3  name3

我有以下查询,我认为它是 (1),但我不太确信(因为它返回的行数看起来太低):

select id, name
from books
left join editions e1 on ( books.id = e1.bookid and e1.edtype = 'paperback')
left join editions e2 on ( books.id = e2.bookid and e2.edtype = 'hardback')
where e1.edtype is not null
and e2.edtype is not null
group by b_id
;

虽然我现在只查看两个属性,但如果能够将其扩展到版本表中的多个匹配属性,那就太好了。

非常感谢您的帮助。

最佳答案

让我们从您的查询开始,稍微改进一下以使用表别名并具有不同的列名称:

select b.id as book_id, b.name, e.id as edition_id, e.edtype
from books b join
editions e
on b.id = e.bookid;

您想要查找书籍,因此建议按书籍进行聚合。然后我们需要做一些事情来理解edtype。试试这个:

select b.id as book_id, b.name,
(case when min(edtype) = max(edtype)
then min(edtype)
else 'Both'
end) as EdTypes
from books b join
editions e
on b.id = e.bookid;
group by b.id, b.name;

关于mysql - 从相关表中选择匹配的属性对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21247144/

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