Sql查询查找歌曲表中没有歌曲的专辑记录

时间:2016-06-13 03:30:27

标签: c# sql sqlite

我在C#中使用sqlite数据库并需要有关sql查询的帮助,我不知道我在单个查询中是否可以得到我当前的解决方案是非常低效和差我把它放在结束但首先是我的问题...

我有两张表歌曲和专辑,表格如下所示

我需要编写一个查询来获取歌曲表中没有歌曲的所有专辑记录......

    Songs

    Artist           Album         Filename        
    Taylor Swift     Red           track1.mp3      
    Taylor Swift     Red           track2.mp3      
    Taylor Swift     Fearless      track1.mp3      
    Taylor Swift     Fearless      track2.mp3    
    Shakira          GrandesExitos track1.mp3


    Albums

    Artist           Album 
    Taylor Swift     Red    
    Taylor Swift     Fearless  
    Taylor Swift     Beautiful Eyes  
    Shakira          The remixes
    Jackson          Fearless
    Taylor Swift     The remixes

需要歌曲表中没有歌曲的专辑的所有记录,。

    So in this case the records of Album I need are

    Taylor Swift     Beautiful Eyes  
    Shakira          The remixes
    Jackson          Fearless
    Taylor Swift     The remixes

我目前的解决方案效率很低,如下所示,我只需要查询帮助而不是C#代码。

    dt = db.GetDataTable(String.Format("select distinct artist, album from files");

    foreach (DataRow r in dt.Rows)
    {
       string artist = (string)r[0];
       string album = (string)r[1];
       //I have create a status column in the Albums table to solve this problem
       query = string.Format("update Albums set status = {0} where artist = '{1}' and album = '{2}'", 1, artist, album);

       int nModified = db.ExecuteNonQuery(query);
     }
     // Then I get all records from Albums whose status is not 1
      dt = db.GetDataTable(select * from Albums where status = 0");

     }

4 个答案:

答案 0 :(得分:3)

您可以使用SQL语句EXISTS来检查特定专辑是否不存在歌曲:

SELECT alb.Artist, alb.Album
FROM Albums alb
WHERE NOT EXISTS (
    SELECT 1 
    FROM Songs s 
    WHERE s.Artist = alb.Artist AND s.Album = alb.Album
)

此SQL语句返回表Album中的所有记录,这些记录在表Songs中没有相关记录。

答案 1 :(得分:-1)

你可以试试这个

{{1}}

答案 2 :(得分:-1)

SELECT artist,album FROM Albums WHERE album NOT IN(SELECT DISTINCT Album FROM songs)

答案 3 :(得分:-1)

不要忘记加入。

select
    album.Artist, album.Album
from
    Albums album
    left outer join Songs song
        on album.Artist = song.Artist and album.Album = song.Album
where
    song.Filename is null -- if it's valid for some reason to have a null song name, just change this to song.Artist is null

这样您就不需要嵌套查询。