开发者

Msql Select and group from db where team_1 and team_2 are the same but reversed in the entry

I need to select from database team_1 and team_2 (football game fixtures) and group by games

 $query = mysql_query("SELECT * FROM fixtures 
                       GROUP B开发者_StackOverflow社区Y team_1 
                       ORDER BY match_date 
                       LIMIT 0,10") or die(mysql_error());

Works fine, however, the football fixtures will be entered via users therefore, someone could enter eg

england v wales and someone could enter wales v england

They are obviously the same game, how can I group together matches if team_1(england) v team_2(wales) is the same as team_1(wales) v team_2(england)


SELECT field1, field2, match_date, ......
       ,GREATEST(team_1,team_2) as team1
       ,LEAST(team_1,team_2) as team2
       ,field6, field7
FROM fixtures
GROUP BY team1
ORDER BY match_date
LIMIT 10 OFFSET 0;


You should probably have some sanity checking on input, to make sure the game is not yet in the database:

$my_team = mysql_real_escape_string(...);
$other_team = mysql_real_escape_string(...);
SELECT team_1, team_2, match_date 
FROM fixtures
WHERE match_date = $match_date 
  AND ((team_1 = '$my_team' AND team_2 = '$other_team' ) OR
       (team_1 = '$other_team' AND team_2 = '$my_team' ));

After this, if this query does not match, it's OK to insert the record. Typically, you'll insert it with the team that plays 'home' first?

Anyway, if you then want to search the match for team 'foo' on 19th of September, you'll do this:

SELECT team_1, team_2, match_date FROM fixtures
WHERE match_date = '2011-09-19' AND
(team_1 = 'foo' OR team_2 = 'foo');`

Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜