duannei1477 2012-07-15 18:35
浏览 18
已采纳

简单的sql多表查询

I am programming a chat room on my site but I am really new to php. I want users to be able to chat with the users that played in the same teams of a game (knowing that users can have participated together to differents team) and who work in the same area.

Assume there are three tables : the account user's table, the area's t able, games'table

I have a function that returns my query that looks like

function myfunction($userid){

$games_user=mysql_query('select theme from games where games.userid="'.$userid.'"');  
$games_theme = mysql_fetch_array($games_user);

$sql = ("select  userid, username, area.userid 

    from account 
        left join area
            on account.userid = area.userid    

        left join games
            on account.userid = games.userid

    where account.userid <> '".mysql_real_escape_string($userid)."' and '".(in_array(games.theme,$games_theme))."' and area.userid=1 
 );
 return $sql;
}

Reformatted:

$sql = "
SELECT userid, username, area.userid 
FROM account 
LEFT JOIN area ON account.userid = area.userid    
LEFT JOIN games ON account.userid = games.userid
WHERE account.userid <> '".mysql_real_escape_string($userid)."'
  AND '".(in_array(games.theme,$games_theme))."'
  AND area.userid = 1 
";

But it really doesn't work, I think I have syntax problems. I don't really understand how in_array is indexed, and I don't know how to do in a simpler way that query

Can anybody help ?

  • 写回答

1条回答 默认 最新

  • dongzun9958 2012-07-15 18:54
    关注

    I'm still not entirely sure what you are doing, but I think this is what you want; you can do this in a single query:

    <?php
    function myfunction($userid){
        $id = mysql_real_escape_string($userid);
        $sql = "SELECT  userid, username, area.userid 
            FROM account 
                LEFT JOIN area
                    ON account.userid = area.userid    
                LEFT JOIN games
                    ON account.userid = games.userid
            WHERE account.userid<>'$id' AND area.userid=1
                AND games.theme IN (SELECT theme FROM games WHERE games.userid='$id')
        ";
        return $sql;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置