如何加入3个选择查询?

时间:2012-06-02 08:17:18

标签: sql database

如何加入这3个查询?

select gameid, type, Player1, Player2, Player3, Player4, Player5 
from tbl_game 
where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + 
      " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' 

select Player1, Player2, Streaks 
from tbl_streaks 
where gameid = [gameid from first query]

select userid, userid, Facebookid, points 
from tbl_userinfo 
where userid = [players from first query]

userid作为参数传递。

我不知道..

请帮帮我。

3 个答案:

答案 0 :(得分:1)

这应该做你想要的:

select g.gameid, g.type, g.Player1, g.Player2, g.Player3, g.Player4, g.Player5, s.Player1, s.Player2, s.Streaks, u.userid, u.Facebookid, u.points
FROM tbl_game g
JOIN ( select Player1, Player2, Streaks from tbl_streaks) s ON s.gameid = g.gameid
JOIN ( select userid, userid, Facebookid, points from tbl_userinfo ) u ON u.userid = (g.Player1 OR g.Player2 OR g.Player3 OR g.Player4 OR g.Player5)
where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + 
      " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' 

然而,这是一个糟糕的设计,有很多列有n个播放器,它们应该是一个专用表的行......

答案 1 :(得分:1)

select tg.gameid, tg.type, tg.Player1, tg.Player2, tg.Player3, tg.Player4
     , tg.Player5, ts.Streaks, tu.userid, tu.Facebookid, tu.points 
  from tbl_game tg 
 inner join tbl_streaks ts 
    on ts.gameid = tg.gameid 
 inner join tbl_userinfo tu 
    on ( tg.Player1 = tu.userid 
          or tg.Player2 = tu.userid 
          or tg.Player3 = tu.userid 
          or tg.Player4 = tu.userid 
          or tg.Player5 = tu.userid
             )
 where tu.userid = " + userid + " 
   and tg.Complete = 'No';

这是根据您的表结构,但我建议您使用模式,以便您可以通过提高性能来进行更好的优化查询。从tbl_game中删除列播放器,并为参与userid到tbl_userinfo的玩家制作单独的查找表。

答案 2 :(得分:0)

select gameid , type ,Player1,Player2,Player3,Player4,Player5 from tbl_game 
Natural Join
(select Player1, Player2, Streaks from tbl_streaks) as t4 on t4.gameid=tbl_game.gameid 
Natural Join
(select userid, userid,Facebookid,points from tbl_userinfo) as t5 on t5.userid="+userid+" 
where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" +  userid + " OR Player5=" + userid + " AND Complete = 'No'