日期:2014-05-16  浏览次数:20569 次

一个关于效率优化的联合查询问题
数据库中有三个表分别是artist ,artist2song ,song

artist中的字段为 id,name
artist2song中的字段为 artistId, songId
song中的字段为id,name

需求举例:
我要先select * from song where name=’七里香‘
然后用查询结果和artist2song联合查询得到 id,name,artistId
然后再和artist联合查询把artist中的name加进去

这个sqlstring怎么写?

------解决方案--------------------
select
   a.name,b. id,b.name,b.artistId
from 
   artist  as a 
inner join artist2song  as b on a.id=b.artistId
inner join song  as c on b.songId=c.id
where
   c.name=’七里香‘

------解决方案--------------------

select *
from song a
   inner join artist2song b
   on a.id=b.songId
   inner join artist c
   on b.artistId=c.id
where a.name='七里香'
????

------解决方案--------------------
三表inner join,然后select *,where中写上对应的筛选条件,然后你再看需要哪些列,就把*换成对应的列,最后distinct
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

select artist.name,song.name
from song inner join on song.id  = artist2song.songId
inner join on artist.id = artist2song.artist.id
where song.name = '七里香'


怎么把最后生成的table里的两个name区分开来?我直接写artist.name as aName报错了 
不需要用as,join之后两个表的name会变成两列的,因为是两列所以我们要取某一列才需要用song.name这样来区分那个name列啊。你试一下吧

我必须要换那个字段,因为要导入datagridview啊,不区分开没法绑定datagridview里的colum
原来你要绑定datagridview,如果确定没办法你就建一个临时表把,自定义字段,把join之后的数据插入临时表,用临时表绑定。试试看吧