多个表的SQL内连接和通过数据库搜索

时间:2014-04-07 07:07:52

标签: php sql join

我在PHP中创建了一个搜索功能,我有三个表,我想加入一个表;这三个表格如下:

band
ID | bands
---+----------
 1 | Muse
 2 | Coldplay
 3 | etc.

release
ID | releases
---+----------
 1 | Showbiz
 2 | Origin of Symmentry
 3 | etc.

track
ID | tracks
---+-----------
 1 | Sunburn
 2 | Muscle Museum 
 3 | etc.

我希望将这些表放入其中:

discografic
ID | band_id  | release_id  | track_id
---+----------+-------------+---------
 1 | 1        | 1           | 1
 2 | 1        | 1           | 2
 3 | etc.

因此,带有SQL代码的表如下所示:

discografic
ID | bands    | releases    | tracks
---+----------+-------------+---------
 1 | Muse     | Showbiz     | Sunburn
 2 | Muse     | Showbiz     | Muscle Museum
 3 | etc.

我想INNER JOIN这些表格。我加入了一个,但我无法弄清楚最后加入的方式。

SELECT * 
FROM band
INNER JOIN discografic 
ON band.id = discografic.band_id

这应该有自己的问题;我也希望能够搜索这个数据库,但只有结果显示一次,并且每次都引用该频段。例如,如果我搜索"Showbiz",它会给我"Muse",并且只显示一次。

注意:这仅用于测试目的,安全性不是我的担忧。

3 个答案:

答案 0 :(得分:2)

尝试使用此查询:

select d.id,b.bands,r.releases,t.tracks from discografic as d INNER JOIN band as b on 
d.band_id=b.id INNER JOIN release as r on d.release_id=r.id INNER JOIN track as t on 
d.track_id=t.id GROUP BY d.id

答案 1 :(得分:0)

尝试此查询

    Select a.ID,b.bands,c.releases,d.tracks from discografic as a 
    inner join band as b on a.band_id = b.ID
    inner join release as c on a.release_id = c.ID
    inner join track as d on a.track_id = d.ID
    where b.bands = 'Muse'

答案 2 :(得分:0)

使用此查询插入您想要的数据:

Insert into discograpy
(id,bands,releases,tracks)
SELECT band.ID,bands,releases,tracks
FROM band
INNER JOIN releases 
ON band.id = releases.id
inner join track
on band.id = track.id

使用此查询仅显示一个波段:

Declare @releases varchar(50)
Set @releases = 'showbiz'
SElect distinct bands from discograpy where releases = @releases

这里可以传递或设置任何变量来代替showbiz。这是一个例子