【问题标题】:SQL comparing set of information in a columnSQL 比较列中的一组信息
【发布时间】:2009-10-22 00:04:24
【问题描述】:

大家好,我很难正确措辞,这就是为什么我在网上找不到答案的原因,所以我能做的最好的就是举个例子。我有以下数据库表:

ACTORNAME                      SERIESNAME
------------------------------ ------------
baldwin                        found
baldwin                        lost
baldwin                        rocks
baldwin                        sienfield

costelo                        friends
costelo                        prince
costelo                        remember
denzel                         friends
denzel                         prince
denzel                         remember

fox                            found
fox                            friends
fox                            prince
lopez                          found
lopez                          friends
lopez                          prince
lopez                          remember

pitt                           er
pitt                           everybody
pitt                           friends
pitt                           heroes
pitt                           rocks
smith                          friends
smith                          prince
smith                          remember

我想使用一个 SELECT 语句来获取在 smith 播放的所有同一系列中播放的演员姓名。因此,生成的演员姓名应该是:

科斯特洛、丹泽尔和洛佩兹

我什至不确定要使用哪个关键字。我正在查看 JOIN 命令并尝试了 MINUS,我能得到的最接近的是与 smith 播放的系列完全相同的演员名称(在这种情况下,洛佩兹不包括在内,而且是错误的)

这里有另一种解释:

suppose Smith acts in movies X and Y.
Suppose also that actor 

A acts in movies X, Z
B acts in Y
C acts in X, Y, Z
D acts in X, Y

The answer to the query should be actors C and D. 

换句话说,你必须返回那些电影中包含演员史密斯的演员。

寻找正确方向的推动力, 托梅克

【问题讨论】:

    标签: sql database select


    【解决方案1】:

    对不起。我原来的回答误解了你的意图。试试这个:

    select   t2.actorname, 
             count(t2.seriesname) 
    from    mytable t1 
    join    mytable t2 
    on      t1.seriesname=t2.seriesname and t1.actorname='smith' and t2.actorname <> 'smith' group by t2.actorname 
    having  count(t2.seriesname)=(select count(seriesname) from mytable where actorname='smith')
    

    【讨论】:

    • 这将返回 smith 出演过的任何系列中的所有演员。我需要在 smith 出演过的所有剧集中出演过的演员。
    • 没有这个错误......这不是预期的。它会提供额外的行
    • 此语句仅返回曾在 smith 出演过的系列中出演过的演员,不包括在 smith 出演过的所有系列中出演过的演员及更多,应包含在答案。 (我在原来的问题中添加了另一种解释以更清楚地说明问题,就像我说这很难正确表达)
    • 你确定吗?我用上面的示例数据试了一下,得到了包括洛佩兹在内的三个演员。
    • @martin Clayton 我相信“有 count(t2.seriesname)=(select count(seriesname) from mytable where actorname='smith')”这部分限制了正在显示的演员的系列数量必须为 3(史密斯参加过的系列赛的数量)
    【解决方案2】:
    SELECT DISTINCT ActorName 
        FROM dbo.MyTable
        WHERE SeriesName IN (SELECT SeriesName FROM dbo.MyTable WHERE ActorName = 'smith');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多