【问题标题】:Python: use one sqlite query to find the NOT EXISTS resultPython:使用一个 sqlite 查询来查找 NOT EXISTS 结果
【发布时间】:2020-05-11 19:28:23
【问题描述】:

我有一个包含数百万条目的数据集,其中包含歌曲及其艺术家。

我有

a track_id
an artist_id.

有 3 张桌子

tracks (track_id, title, artist_id),
artists(artist_id and artist_name) and
artist_term (artist_id and term).

仅使用一个查询,我必须计算其艺术家没有任何链接词的曲目数量。

更多参考,DB的架构如下:

CREATE TABLE tracks (track_id text PRIMARY KEY, title text, release text, year int, duration real, artist_id text);
CREATE TABLE artists (artist_id text, artist_name text);
CREATE TABLE artist_term (artist_id text, term text, FOREIGN KEY(artist_id) 
REFERENCES artists(artist_id));

如何找到解决方案?请帮忙!

【问题讨论】:

    标签: python sql sqlite pysqlite


    【解决方案1】:

    您可以加入表tracksartists 并左加入表artist_term 以便找到不匹配的artist_ids:

    select count(distinct t.track_id)
    from tracks t
    inner join artists a on a.artist_id = t.artist_id
    left join artist_term at on at.artist_id = a.artist_id
    where at.artist_id is null
    

    WHERE 子句中的条件at.artist_id is null 将仅返回将被计算在内的不匹配行。

    【讨论】:

      【解决方案2】:

      你可以使用not exists:

      select count(*) cnt
      from tracks t
      where not exists (select 1 from artist_term at where at.artist_id = t.artist_id)
      

      就问题而言,您不需要引入artists 表,因为artist_idtracksartist_term 表中都可用。

      为了提高性能,您需要在tracks(artist_id) 上建立一个索引,在artist_term(artist_id) 上建立另一个索引。

      left join 也可以完成工作:

      select count(*) cnt
      from tracks t
      left join artist_term at on at.artist_id = t.artist_id
      where at.artist_id is null
      

      【讨论】:

        【解决方案3】:

        如果我没记错的话,这样的查询可以像其兄弟 SQL 语言一样以类似的方式构建。如果是这样,它应该看起来像这样:

        SELECT COUNT(track_id)
        FROM tracks as t
        WHERE EXISTS (
            SELECT *
            FROM artists AS a
            WHERE a.artist_id = t.artist_id
            AND NOT EXISTS(
                SELECT *
                FROM artist_term as at
                WHERE at.artist_id = a.artist_id
            )
        )
        

        所以这个查询基本上是说:计算不同曲目的数量(由它们唯一的track_id标记),其中有一个艺术家具有相同的artist_id,其中不存在引用artist_term的@987654325艺术家的@。

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 2019-01-12
          • 1970-01-01
          • 1970-01-01
          • 2020-12-27
          • 2011-02-11
          • 2014-11-25
          • 1970-01-01
          • 1970-01-01
          • 2011-04-10
          相关资源
          最近更新 更多