gpt4 book ai didi

mysql - 如何在 group_concat 中进行子查询

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

我有以下数据模型:

`title`

- id
- name

`version`

- id
- name
- title_id

`version_price`

- id
- version_id
- store
- price

这是一个数据示例:

`title`

- id=1, name=titanic
- id=2, name=avatar

`version`

- id=1, name="titanic (dubbed in spanish)", title_id=1
- id=2, name="avatar directors cut", title_id=2
- id=3, name="avatar theatrical", title_id=2

`version_price`

- id=1, version_id=1, store=itunes, price=$4.99
- id=1, version_id=1, store=google, price=$4.99
- id=1, version_id=2, store=itunes, price=$5.99
- id=1, version_id=3, store=itunes, price=$5.99

我想构建一个查询,为我提供所有在 iTunes 上有 version_price 但在 Google 上没有的标题。我该怎么做?这是我目前所拥有的:

select 
title.id, title.name, group_concat(distinct store order by store)
from
version inner join title on version.title_id=title.id inner join version_price on version_price.version_id=version.id
group by
title_id

这给了我一个 group_concat,它显示了我有什么:

id  name    group_concat(distinct store order by store) 
1 Titanic Google,iTunes
2 Avatar iTunes

但是我将如何构造一个查询以包括该项目是否在 Google 上(使用案例语句或任何需要的东西)

id  name    group_concat(distinct store order by store) on_google 
1 Titanic Google,iTunes true
2 Avatar iTunes false

它基本上是执行 group_concat LIKE '%google%' 而不是普通的 where 子句。

这是我当前查询的 SQL fiddle 链接:http://sqlfiddle.com/#!9/e52b53/1/0

最佳答案

使用条件聚合来确定标题是否在指定商店中。

select title.id, title.name, group_concat(distinct version_price.store order by store),
if(count(case when store = 'google' then 1 end) >= 1,'true','false') as on_google
from version
inner join title on version.title_id=title.id
inner join version_price on version_price.version_id=version.id
group by title.id, title.name

count(case when store = 'google' then 1 end) >= 1 在将 1 分配给具有 google 在其中。 (否则它们将被分配为 null 并且 count 忽略空值。)此后,if 检查 count 并对至少有一个 google 商店的标题进行分类。

关于mysql - 如何在 group_concat 中进行子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083605/

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