MySQL重复和不正确的结果

时间:2014-08-26 15:01:42

标签: mysql

我有两张表格如下:

**MUSICIAN**

musicianSurname

musicianForename

musicianNInumber   PK

musicianDOB

musicianAddress1   FK



**MUSICIAN_ADDRESS**

musicianTelNo

MusicianAddress1   PK

musicianAddress2

musicianPostcode

我想查询数据库说“给我看所有音乐家姓名地址和电话号码,这是我的查询:

 SELECT musician.musicianForename, musician.musicianSurname, musician_address.musicianaddress1, musician_address.musicianTelNo
FROM musician
JOIN musician_address;

它返回这样的结果(显然是错误的,所有重复的信息都不匹配)。请有人帮忙!

Angela  Underpants  145 Acacia Avenue   01234567891
Angela  Underpants  26 Bobbo Road   0208562456
Angela  Underpants  45 Underfrock Road  01753526893
Angela  Underpants  9 Simple Drive  01587452326
Jack    Towslon 145 Acacia Avenue   01234567891
Jack    Towslon 26 Bobbo Road   0208562456
Jack    Towslon 45 Underfrock Road  01753526893
Jack    Towslon 9 Simple Drive  01587452326
Terry   Awesome 145 Acacia Avenue   01234567891
Terry   Awesome 26 Bobbo Road   0208562456
Terry   Awesome 45 Underfrock Road  01753526893
Terry   Awesome 9 Simple Drive  01587452326
Brad    Cobra   145 Acacia Avenue   01234567891
Brad    Cobra   26 Bobbo Road   0208562456
Brad    Cobra   45 Underfrock Road  01753526893
Brad    Cobra   9 Simple Drive  01587452326
Lara    Tehabsim    145 Acacia Avenue   01234567891
Lara    Tehabsim    26 Bobbo Road   0208562456
Lara    Tehabsim    45 Underfrock Road  01753526893
Lara    Tehabsim    9 Simple Drive  01587452326
Jennifer    Saunders    145 Acacia Avenue   01234567891
Jennifer    Saunders    26 Bobbo Road   0208562456
Jennifer    Saunders    45 Underfrock Road  01753526893
Jennifer    Saunders    9 Simple Drive  01587452326
Phil    Oades   145 Acacia Avenue   01234567891
Phil    Oades   26 Bobbo Road   0208562456
Phil    Oades   45 Underfrock Road  01753526893
Phil    Oades   9 Simple Drive  01587452326
Pat O'Cake  145 Acacia Avenue   01234567891
Pat O'Cake  26 Bobbo Road   0208562456
Pat O'Cake  45 Underfrock Road  01753526893
Pat O'Cake  9 Simple Drive  01587452326
James   McFab   145 Acacia Avenue   01234567891
James   McFab   26 Bobbo Road   0208562456
James   McFab   45 Underfrock Road  01753526893
James   McFab   9 Simple Drive  01587452326

2 个答案:

答案 0 :(得分:1)

 SELECT musician.musicianForename, musician.musicianSurname,musician_address.musicianaddress1, musician_address.musicianTelNo
FROM  musician_address
JOIN  musician on 
MusicianAddress1.MusicianAddress1 = MUSICIAN.musicianAddress1  ;

我还会重新考虑您的数据库设计。拥有地址的主键不是主键的最佳使用,可能会导致问题。

阅读http://sqlmag.com/database-administration/sql-design-how-choose-primary-key只是关于如何选择主键的众多文章之一。

答案 1 :(得分:0)

SELECT m.musicianForename, m.musicianSurname, 
       ma.musicianaddress1, ma.musicianTelNo
FROM musician m 
JOIN musician_address ma ON ma.musicianaddress1 = m.musicianaddress1;

通过这种方式,您将获得每位音乐家的地址

您需要JOIN

中的条件