简体   繁体   English

简单的sql多表查询

[英]Simple sql multi-table query

I am programming a chat room on my site but I am really new to php. 我在我的网站上编写了一个聊天室,但我对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 我真的不明白in_array是如何编入索引的,而且我不知道如何以更简单的方式进行查询

Can anybody help ? 有人可以帮忙吗?

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;
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM