从两个不同的表mysql中的两行获取结果

时间:2013-07-09 06:24:14

标签: mysql

这是来自足球系统,可以保存游戏的每个游戏,玩家和“日志”以进行统计。

  • “bold_players”是包含播放器的表:id,name,age ...
  • “bold_playlog”是包含游戏所有日志的表格:id,createdate,logtype,playerid ...
    “logtype = 1”是一个目标(只有一个目标 - 每个目标在表格上都有一个帖子/ id“bold_playlog”,所以如果一个游戏有四个目标,那么“bold_playlog”中将有四个帖子具有相同的gameid)

如何按目标排列所有球员名单?

这是我现在的代码,但我想我必须加入这两个表或类似的东西!?:

$data_player = mysql_query("SELECT id, name, goals, playtogoal FROM bold_players ORDER BY name ASC ");
while ($row_player = mysql_fetch_assoc($data_player)) {

$seasonstart = mktime(0, 0, 0, 7, 1, date('Y')-1);

$logplayer = $row_player['id'];
$data_log = mysql_query("SELECT id, createdate, logtype FROM bold_playlog WHERE logplayer=$logplayer AND logtype = 1 AND createdate > $seasonstart ");
$getresult = mysql_num_rows($data_log);

if($getresult > 0) {

echo 'the result';

}}

2 个答案:

答案 0 :(得分:0)

也许试试这个..我猜它一定是这样的

SELECT  name, goals, sum(playtogoal) as goals, createdate, logtype 
FROM bold_players as ps LEFT JOIN bold_playlog as pl ON ps.id=pl.logplayer
WHERE pl.logtype = 1 AND pl.createdate > $saesonstart
GROUP BY ps.id ORDER BY name ASC 

我会进行LEFT JOIN,因为可能会有没有进球的球员,而且他们也会出现

答案 1 :(得分:0)

一个简单的LEFT JOIN应该这样做,这首先命令大多数目标是DESC部分,首先使用ASC进行最少的目标。

SELECT a.*, COUNT(b.playerid) goals
FROM bold_players a
LEFT JOIN bold_log b
  ON b.playerid = a.id
 AND b.logtype=1
GROUP BY a.id, a.name, a.age
ORDER BY COUNT(b.playerid) DESC

An SQLfiddle to test with

如果您还需要更多日志类型,则必须稍微更改查询。如果offside是logtype 2,则查询将是;

SELECT a.*, 
  COALESCE(SUM(b.logtype=1), 0) goals, 
  COALESCE(SUM(b.logtype=2), 0) offsides
FROM bold_players a
LEFT JOIN bold_log b
  ON b.playerid = a.id
-- AND (b.logtype=1 OR b.logtype=2)      -- for speedup if there are many types
GROUP BY a.id, a.name, a.age
ORDER BY COALESCE(SUM(b.logtype=1), 0) DESC

Another SQLfiddle