【发布时间】:2017-12-12 17:58:17
【问题描述】:
我有 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
我需要获取具有多个analysistype 的所有analysistext 值,以及与具有多个analysistype 的这些analysistext 关联的所有entries。
所以在上面的数据中,我们想要结果
my_date text type
2011-4 blah A
2011-4 blah B
因为那是具有不止一种类型的文本。
下面的查询有效,但是使用子查询来识别大于analysisType 的analysisText 值感觉效率低下:
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 by 和 having count。这可能吗?
【问题讨论】:
标签: mysql sql join count having