-2

我有两张桌子

用户

在此处输入图像描述

游戏

在此处输入图像描述

我的要求

[
 {
   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 代码。

4

3 回答 3

1

使用此查询完美地工作

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

在此处输入图像描述

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

于 2013-09-26T06:45:49.157 回答
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

我不尝试查询,但它应该可以工作

编辑

根据@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
于 2013-09-26T06:49:23.350 回答
0

你必须使用内连接而不是左连接

$result = mysql_query("SELECT *
FROM users 
INNER JOIN games ON users.games=games.id 
GROUP BY users.id") or die(mysql_error());
于 2013-09-26T06:28:50.780 回答