我正在尝试从数据库中的2个不同表中输出数据,这些表由连接表连接。
Table 1: musician
Columns: musicianID, surname, fName
Table 2: musician_band
Columns: musicianID, bandID
Table 3: band
Columns: bandID, bandName, genre, yearFormed, origin
刚开始我想输出:
fName, bandName
我尝试使用此查询:
SELECT DISTINCT fName, bandName
FROM musician_band
JOIN musician ON musician.musicianID = musician_band.musicianID
JOIN band ON band.bandID = band.bandID
但是不是给我一个音乐家和他们所在乐队的列表,而是重复数据库中第一个音乐家的名字,然后是右边的乐队名称,这是重复的数据库中的每个乐队,即使不应该是那个特定的音乐家和乐队之间的关系。像这样:
fname bandName
musician1 band1
musician1 band2
musician1 band3
musician2 band1
musician2 band2
musician2 band3
等...
我如何纠正这一点,以便它只输出正确乐队中的音乐家?
答案 0 :(得分:2)
您还没有正确加入表格
JOIN band ON band.bandID = band.bandID
将为乐队中的每一行获得1行。
请改为尝试:
SELECT DISTINCT fName, bandName
FROM musician_band
JOIN musician ON musician.musicianID = musician_band.musicianID
JOIN band ON band.bandID = musician_band.bandID
您甚至可以使用此解决方案删除关键字DISTINCT
答案 1 :(得分:2)
您的别名存在问题。您需要JOIN中每个引用表的不同别名:
此示例查询可以正常工作:
SELECT DISTINCT fName, bandName
FROM @musician_band mb
JOIN @musician m ON m.musicianID = mb.musicianID
JOIN @band b ON mb.bandID = b.bandID
在SQL Server中使用此示例:
declare @musician table(musicianID int, surname varchar(50), fName varchar(50));
insert into @musician(musicianID, surname, fName
) values
( 1, 'Pete Doherty', 'Pete Doherty')
, ( 2, 'Damon Albarn', 'Damon Albarn')
declare @musician_band table(musicianID int, bandID int);
insert into @musician_band(musicianID, bandID) values
(1, 1)
, (1, 2)
, (2, 3)
, (2, 4)
declare @band table(bandID int, bandName varchar(50), genre varchar(50), yearFormed int, origin varchar(50));
insert into @band(bandID, bandName, genre, yearFormed, origin
) values
( 1, 'The Libertines', '', 0, '')
, (2, 'Babyshambles', '', 0, '')
, (3, 'Blur', '', 0, '')
, (4, 'Gorillaz', '', 0, '')
输出结果为:
fName bandName
Damon Albarn Blur
Damon Albarn Gorillaz
Pete Doherty Babyshambles
Pete Doherty The Libertines
只需用您自己的表替换@tablename即可。 DISTINCT
在这种情况下有用吗?