用于从2个表中获取数据的PHP mysql查询

时间:2013-09-26 06:22:57

标签: php mysql sql json

我有两张桌子

用户

enter image description here

游戏

enter image description here

我的要求

[
 {
   users:{
     id: "1",
     user: "user1",
     games:[
       {
         id : "1",
         game_names : "football"
       }
       {
         id : "2",
         game_names : "cricket"
       }
       {
         id : "3",
         game_names : "athletics"
       }
       {
         id : "4",
         game_names : "badminton"
       }
     ]
   }
   users: {
     id : "2",
     user : "user2",
     games :[
       {
         id : "3",
         game_names : "athletics"
       }
       {
         id : "4",
         game_names : "badminton"
       }
       {
         id: "5",
         game_names : "basketball"
       }
     ]
   }
 }
]

我现在使用的是什么

<?php 
$result = mysql_query("SELECT *,games.game_names as games
FROM users 
LEFT JOIN games ON users.games=games.id 
GROUP BY users.id") or die(mysql_error());

while($user = mysql_fetch_array($result, MYSQL_ASSOC)) {        
    $users[] = array(
                'user'=>array(
                    'id' => $user['id'],
                    'user' => $user['user'],                        
                    'games' =>  $user['games']          
                )
    );  
} 
$output = json_encode(array('statics' => $users));
echo $output;
    ?>

但我正在

{
 statics: [
   {
    users: {
       id: "1",
       user: "user1",
       games: "1,2,3,4"
    }
   },
   {
    users: {
     id: "2",
     user: "user2",
     games: "3,4,5"
   }
  }
 ]
}

但我无法获得第二阵列游戏

我应该如何更改我的代码php代码。

3 个答案:

答案 0 :(得分:1)

使用此查询完美运行

SELECT users.*,games.game_names,games.id as games_id
FROM users 
LEFT JOIN games ON FIND_IN_SET(games.id,users.games)

enter image description here

现在根据您的要求设置php代码

答案 1 :(得分:1)

嗯,我想你不能直接在查询中做到这一点。而不是这个,你应该规范你的模型:

users
user_id
user_name

users_games
user_id
game_id

games
game_id
game_name

对于您的示例,数据将是:

users:
1,user1
2,user2

users_games:
1,1
1,2
1,3
1,4
2,3
2,4
2,5

games:
1,game1
2,game2
3,game3
4,game4
5,game5

规范化后,您可以执行此查询,从而为您提供您想要的内容

SELECT users.user_id, users.user_name, GROUP_CONCAT(games.game_names)
FROM users INNER JOIN users_games ON users.user_id=users_games.user_id
INNER JOIN games ON users_games.game_id = games.game_id GROUP BY users.user_id

我不尝试查询,但应该可以使用

<强> EDITED

根据@ShaktiPatel,你可以使用find_in_set,(我不知道函数FIND_IN_SET)和group_concat:

SELECT users.*,GROUP_CONCAT(games.game_names)
FROM users 
INNER JOIN games ON FIND_IN_SET(games.id,users.games) GROUP BY users.id

答案 2 :(得分:0)

您必须使用内部联接而不是左联接

$result = mysql_query("SELECT *
FROM users 
INNER JOIN games ON users.games=games.id 
GROUP BY users.id") or die(mysql_error());