简体   繁体   English

mysql如何选择在另一列中具有相同值且在另一表的列中具有相同值的字段?

[英]mysql How to select fields that have the same value in another column AND the same value in another table's column?

This is part of a homework to be perfectly honest, not of such importance, but still. 坦白地说,这是家庭作业的一部分,虽然不那么重要,但仍然如此。 So, lets suppose we have the following tables: 因此,假设我们有以下表格:

        Song                                      Singer_prod

composer     title                            singer      sing_title
   A          a1                                S1            b1
   A          a2                                S3            c3
   B          b1                                S3            c1
   C          c1                                S1            a1
   C          c2                                S1            a2
   C          c3                                S3            c2 
                                                S2            a1

Now, the question is to select those composers, whose every title has been sang by only one singer. 现在,问题是选择那些只有一个歌手演唱过所有歌名的作曲家。 For instance, composer B has only one title, b1 , sang only by S1 . 例如,作曲家B只有一个标题b1 ,仅由S1演唱。

Also, composer C has written c1, c2,c3 , all sang only by S3 . 另外,作曲家C编写了c1,c2,c3 ,所有这些仅由S3演唱。 Those two composers should show up in the results. 那两位作曲家应该出现在结果中。

In contrast, from composer's A songs, a2 was sang only by S1 but a1 was sang both by S1 and by S2 , so A shouldn't show up in the results. 相反,在作曲家的A歌曲中, a2仅由S1演唱,而a1既由S1也由S2演唱,因此A不应该出现在结果中。

I've tried countless combinations of nested SELECTS, GROUP BYs and WHEREs, with no luck so far. 我尝试了无数嵌套SELECTS,GROUP BY和WHERE的组合,但到目前为止还没有运气。 The only thing i'm pretty sure is that a count(singer)=1 should be needed somewhere, so far fruitlessly used though. 我唯一确定的唯一事情是,某个地方需要一个count(singer)= 1,尽管到目前为止却毫无用处。

Any help would be greatly appreciated! 任何帮助将不胜感激!

SELECT Composer, Singer FROM Song x
INNER JOIN Singer_prod y on x.title = y.sing_title
GROUP BY Composer, Singer
HAVING COUNT(Distinct Singer) = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM