理解规范化&重复 - 我猜我不 - 添加艺术家&标题ID

时间:2017-06-13 20:30:11

标签: mysql database join database-normalization

我从一张桌子开始,列出了1958年到1980年间按日期排名前100首的歌曲。每个日期都有100首唱片。很明显,随着歌曲每周改变位置,很多都会重复。此外,艺术家将被复制(想想猫王)多次。表中有大约116,000条记录。

此表包含以下字段

uniq,
date,
artist,
title,
position

为了消除重复(按照我的理解进行规范化)我修改了表格,使其现在看起来像这样

uniq,
date,
artistcode,
titlecode,
position

有两个新表艺术家和头衔。 艺术家看起来像这样

artist,
artistcode

标题看起来像这样

title,
titlecode

为了开始正确的方向,我只想重新组合(加入)这些表,以便我有一个看起来像原始表的视图,即

uniq,
date,
artist,
title,
position

并拥有这116000条记录。在阅读了几本书并使用了几本教程之后,我得出的结论是我对规范化应该做什么有误解,或者我只是朝着错误的方向前进。

非常感谢用于创建视图的SQL语法。

2 个答案:

答案 0 :(得分:1)

要使用多个表返回原始输出,您可以使用以下语法JOINs

SELECT s.uniq, s.date, a.artist, t.title, s.position
FROM songs AS s
JOIN artists AS a ON a.artistcode = s.artistcode
JOIN titles AS t ON t.titlecode = s.titlecode

如果您尝试消除重复的歌曲条目,可以将其添加到查询中:

GROUP BY t.title

答案 1 :(得分:1)

什么“重复”? There is nothing wrong per se with the same value appearing multiple times.你需要开始阅读一些关于information modeling and relational databases的学术教科书/幻灯片/课程。

表中或不在表中的每一行都会显示有关情况的声明。 当{em>同一个表的多行说明情况相同时时,normalization地址出现的“重复”和“冗余”问题就会出现。 (可能会或可能不会涉及多次出现的子行数。)

例如:如果您有一个像这样的表,但有一个额外的列和一个给定的艺术家/标题组合总是出现在该列中具有相同的值(就像艺术家从来没有多个具有相同标题图表的记录和你添加了每个录音的播放时间)然后就会出现问题。 (“...并且记录艺术家 / 标题 时间分钟”“如果您有一个像这样的表,但有一个额外的列并且其中的值始终以相同的艺术家/标题组合出现(如果您添加了录制ID),那么就会出现问题。 (“......并且录制录制代码是艺术家艺术家的标题标题”)现在没有问题。你期望什么作为答案?答案是,规范化表示没有问题,并且您的印象不会通过规范化来实现。

Normalization does not involve replacing values by ids.引入的id值与它们识别/替换的值具有完全相同的外观模式,因此不会“消除重复”,并且它会在新表中添加更多“重复”ID。 The original table as a view is a projection of a join of the new tables on equality of ids.(您可能希望使用id来更容易更新或数据压缩(等等),代价是更多的表和连接(等)。这是一个单独的问题。)

-- hit `uniq` is title `title` by artist `artist` at position `position` on date `date`
/* FORSOME h.*, a.*, t.*,
    hit h.uniq is title with id h.titlecode by artist with id h.artistcode
        at position h.position on date h.date
AND artist a.artist has id a.artistcode AND h.artistcode = a.artistcode
AND title t.title has id t.titlecode AND h.titlecode = a.title
AND `uniq` = h.uniq AND `title` = t.title AND `artist` = a.artist
    AND `position` = h.position AND `date` = h.date
*/
/* FORSOME h.*, a.*, t.*,
    Hit(h.uniq, h.titlecode, h.artistcode, h.position, h.date)
AND Artist(a.artist, a.artistcode) AND h.artistcode = a.artistcode
AND Title(t.title, t.titlecode) AND h.titlecode = a.title
AND `uniq` = h.uniq AND `title` = t.title AND `artist` = a.artist
AND `position` = h.position AND `date` = h.date
*/
create view HitOriginal as
select h.uniq, h.date, a.artist, t.title, h.position
from Hit h
join Artist a on h.artistcode = a.artistcode
join Title t on h.titlecode = t.titlecode