gpt4 book ai didi

mysql - SQL - GROUP BY 有计数,连接多个表

转载 作者:行者123 更新时间:2023-11-30 21:49:53 26 4
gpt4 key购买 nike

我有 4 个表:

Entries:
id
year
day

AnalysisText:
id
text
entries_id

AnalysisType:
id
type

AnalysisTextTypes:
id
analysistext_id
analysistype_id

示例数据:

entries     
id year day
1 2010 1
2 2011 4
3 2012 6


AnalysisText
id text entries_id
1 blah 2
2 more blah 1
3 blah blah 1

AnalysisType
id type
1 A
2 B
3 C

AnalysisTextTypes
id analysistext_id analysistype_id
1 1 1
2 1 2
3 2 3
4 3 1

我需要获取所有具有多个 analysistypeanalysistext 值,以及与这些 关联的所有 entries具有多个 analysistype 的 analysistext

所以在上面的数据中,我们要的是结果

my_date text    type
2011-4 blah A
2011-4 blah B

因为那是具有不止一种类型的文本。

下面的查询有效,但使用子查询来识别超过 analysisTypeanalysisText 值感觉效率低下:

select  
CONCAT(e.year, '-', e.day) as my_date,
x.text,
y.type
from entries e
join analysistext x on e.id = x.entries_id
join analysistext_types xy on xy.analysistext_id = x.id
join analysistype y on y.id = xy.analysistype_id
where xy.analysistext_id in (
select analysistext_id
from analysistext_types
group by analysistext_id
having count(analysistype_id) > 1
) order by my_date, analysis_text, type;

我想要一个查询,我们从连接的表中SELECT感兴趣的字段,然后直接在表上执行group byhaving count加入了。这可能吗?

最佳答案

您可以使用自连接来完全避免子查询

select concat(e.year, '-' ,e.day), at.text ,ant.type
from AnalysisText at
join entries e on at.entries_id = e.id
join AnalysisTextTypes att on att.analysistext_id = at.id
join AnalysisType ant on att.analysistype_id = ant.id
join AnalysisTextTypes att2 on att2.analysistext_id = att.analysistext_id
group by att2.analysistext_id
having count(att2.analysistext_id) > 1

关于mysql - SQL - GROUP BY 有计数,连接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47778816/

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