【问题标题】:Outputting the name of the column in SQLite在 SQLite 中输出列的名称
【发布时间】:2021-12-02 13:15:01
【问题描述】:

我已经创建了两个表,现在我想找到为每个平台(Hulu、迪士尼和 Netflix)带来最高收入的电影。这里的问题是我不知道如何输出平台的名称,因为它是一个列标题。谁能帮帮我?

CREATE TABLE "StreamedMovies" (
 "Title" TEXT, 

 "Netflix" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise

 "Hulu" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise


 "Disney" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise

 "ScreenTime" REAL, 

 PRIMARY KEY("Title")
)

CREATE TABLE "MovieData" (
 "Title" TEXT, 
 "Genre" TEXT, 
 "Director" TEXT, 
 "Casting" TEXT, 
 "Rating" REAL, 
 "Revenue" REAL,
 PRIMARY KEY("Title")
)

【问题讨论】:

  • 糟糕的设计会导致复杂的查询和糟糕的性能。更改数据库的设计。您只需要 1 列而不是 3 列(如果您想包含更多平台,则需要更多列)。

标签: sql database sqlite


【解决方案1】:

你必须写一个案例陈述。

select
  Title,
  case
    when Netflix == 1 then 'Netflix'
    when Hulu = 1 then 'Hulu'
    when Disney = 1 then 'Disney'
  end as Platform
from StreamedMovies

这表明您的设计存在缺陷。若干缺陷。例如,没有什么可以阻止一行拥有多个平台。或者没有平台。或者将平台设置为 42。

相反,添加一个平台表和一个join table 以指示哪些电影在哪些平台上流式传输。

我们会解决一些其他问题。

  • 标题可以更改。使用简单的整数主键。
  • 不要引用列名和表名,这会使它们区分大小写。
  • 声明您的外键。
  • 使用 not null 表示需要重要数据。
-- The platforms available for streaming.
create table platforms (
  id integer primary key,
  name text not null
);

insert into platforms (id, name)
  values ('Netflix'), ('Hulu'), ('Disney+');

-- The movies.
create table movies (
  id integer primary key,
  title text not null
);

insert into movies (title) values ('Bad Taste');

-- A join table for which platforms movies are streaming on.
create table streamed_movies (
  movie_id integer not null references movies,
  platform_id integer not null references platforms
);

insert into streamed_movies (movie_id, platform_id) values (1, 1), (1, 3);

select
  movies.title, platforms.name
from streamed_movies sm
join movies on sm.movie_id = movies.id
join platforms on sm.platform_id = platforms.id

title      name   
---------  -------
Bad Taste  Netflix
Bad Taste  Disney+

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多