1

我正在努力在 mySQL 或 SQL Server 中加入多个表并保持快速的性能。我有这张桌子:

餐桌歌曲

songID|songName
---------------
01|diamond
02|goodbye

表歌手歌曲

 songID|singerID
 ---------------
 01|15
 02|22

表歌手

singerID|singerName|Sex
------------------------
15| Rihanna | F
22| Air Supply | M

我想要这样的结果:

songID|songName|singerName|Sex
------------------------------ 
01|diamond|Rihanna|F 
02|goodbye|Air Supply| M

我的查询是这样的

SELECT s.songID, s.songName, sr.singerName, sr.Sex 
FROM songs s, singersong ss, singer sr
WHERE 
ss.songID = s.songID AND 
ss.singerID = sr.singerID
ORDER BY s.songID

而且它的执行速度非常非常慢.. 有没有办法让这个查询更简单或更高效?

非常感谢您的帮助.. LL

4

3 回答 3

1

指定加入的条件。您当前的查询,取决于优化器的突发奇想,可能会在所有表之间产生笛卡尔积,然后过滤结果。还要确保您正确设置了索引和 FK。

SELECT s.songID, s.songName, sr.singerName, sr.Sex 
FROM songs s
LEFT JOIN singersong ss ON s.songID = ss.songID
LEFT JOIN singer sr ON ss.singerID = sr.singerID
ORDER BY s.songID

如果您不希望在相关表中没有匹配条目时返回空值,请替换LEFT JOIN为。INNER JOIN

于 2013-06-06T06:17:50.620 回答
0

Your syntax is not the modern style, but it should work fine. For performance, make sure you have indexes on all the columns used for the join: songID and singerID.

于 2013-06-06T06:22:16.940 回答
0

It's not enough just have indexes, you need multi-column index that spans the join table in the direction of travel, i.e if you are starting from Song and going to Singer the index would be: INDEX songSinger (songID,singerID)

And if you were querying from Singer to Song, the index would be: INDEX SingerSong (singerID,songID)

If you only have one column indexed, then MySQL will use the index to get the set of results from table singersong, load the results and then scan down that list of results for the next step of the join.

However, If you have an index that spans two columns, MySQL doesn't even load the join table, it just uses the index.

于 2016-03-02T23:16:53.873 回答