gpt4 book ai didi

mysql - 查询多对多,其中连接表上只有 1 个结果

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

我有一个与 Groupe 表存在多对多关系的 Statistiquecolle 表。我想要获取仅链接到 id 1 的 Groupe 的所有 StatistiqueColle 行。

我可以选择链接到 id 1 的 Groupe 的所有 StatistiqueColle 行,但我也有链接到 id 1 的 Groupe 和其他组的行。

这是我的查询(statistiquecolle_groupe 是 statistique colle 和 groupe 之间的链接表):

SELECT sc.id, sc.colle_id, sc.effectif, sc.moyenne, sc.mediane, sc.note100, sc.major, sc.minor
FROM statistiquecolle sc
INNER JOIN statistiquecolle_groupe scg ON sc.id = scg.statistiquecolle_id
WHERE scg.groupe_id = 1
AND sc.id = scg.statistiquecolle_id

我考虑过在 where 子句中计算行数,并仅选择有一个 statistiquecolle_groupe 行的 StatistiqueColle 行,但我不知道该怎么做。

编辑:表结构 enter image description here

最佳答案

尝试这样做,我更改了联接中的表顺序,设置了左联接并删除了 where 中的 and 子句,因为您已经在 ON 子句中使用了它:

SELECT sc.id, sc.colle_id, sc.effectif, sc.moyenne, sc.mediane, sc.note100, sc.major, sc.minor
FROM statistiquecolle_groupe scg
LEFT JOIN statistiquecolle sc ON sc.id = scg.statistiquecolle_id
WHERE scg.groupe_id = 1 AND
sc.id NOT IN (SELECT sc1.id
FROM statistiquecolle_groupe scg1
LEFT JOIN statistiquecolle sc1 ON sc1.id = scg1.statistiquecolle_id
WHERE scg1.groupe_id != 1)

立即尝试。希望它有效

关于mysql - 查询多对多,其中连接表上只有 1 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215778/

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