I'm trying to do an API for an application. This is my Mysql structure.
mysql> desc player;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | NO | UNI | NULL | |
| password | varchar(30) | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0,00 sec)
mysql> desc team;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0,00 sec)
mysql> desc player_team;
+--------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| player | int(11) | NO | MUL | NULL | |
| team | int(11) | NO | MUL | NULL | |
+--------+---------+------+-----+---------+----------------+
3 rows in set (0,00 sec)
And I'm executing this node code with node-mysql package:
var express = require('express');
var router = express.Router();
var connection = require('../lib/mysql.js');
router.get('/', function(req, res, next) {
var query = 'select p.name as player, t.name as team from player p join player_team pt on p.id=pt.player join team t on pt.team = t.id order by player;';
connection.query(query , function(error, result){
if (error){
res.send(error);
}
else {
res.json(result);
}
});
});
And it the next JSON:
[
{
"player":"arzeus",
"team":"Origen"
},
{
"player":"haton",
"team":"Fnatic"
},
{
"player":"haton",
"team":"Origen"
},
{
"player":"loko",
"team":"Fnatic"
}
]
Which is the best way to get the player "haton" both teams in an array? I know I can do it manually, but i would like to know if there's already some way to do it automatically.
[
{
"player":"arzeus",
"team":"Origen"
},
{
"player":"haton",
"teams" {
"team":"Fnatic",
"team":"Origen"
}
},
{
"player":"loko",
"team":"Fnatic"
}
]
答案 0 :(得分:1)
与MySQL最接近的是GROUP_CONCAT。
请注意,无论如何都无法获得所需的输出(如果您希望在JavaScript中使用它),因为对象不能具有重复的属性名称:
{
"team":"Fnatic",
"team":"Origen"
}
你是说一个对象数组?像这样:
"teams": [
{"team": "Fnatic"},
{"team": "Origen"}
]
或者只是一组球队:
"teams": ["Fnatic" "Origen"]
无论如何,为了让你更接近你所追求的东西,GROUP_CONCAT
最终会给你:
{
"player":"haton",
"teams" "Fnatic,Origen"
}