从不同的列中选择具有相同值的行

时间:2014-10-31 07:48:19

标签: php mysql

假设我有一个数据库存储来自最近的足球比赛的数据与我的朋友。我不按特定顺序存储每行朋友的姓名。如何在不必遍历每一行查找每列中的每个值的情况下将数据拉回来?

这是一个示例表:

gameID   player1     player2    player3   .......
1        John        Chance     Gordon
2        Jim         Gordon     John
3        Derek       Chance     Richard

我如何根据他在任何列中选择John所玩的行?我计划将它们放入PHP数组并计算它们的外观。检查每个列的最有效方法是什么,而不是像:

$playerarray=array{'Derek','John','Gordon','Richard','Jim','Chance',....}
foreach($playerarray as $key => $value){
    //Is this even horribly inefficient?
    $sql = mysql_query(SELECT * from game_table WHERE player1='$value' OR player2='$value' OR player3='$value'...)
}

2 个答案:

答案 0 :(得分:1)

您需要的SQL语句如下:

SELECT * FROM game_table WHERE CONCAT_WS(',', player1, player2, player3) LIKE '%John%'

此查询将返回John进入的行的所有字段:首先将3个玩家的列与逗号连接,然后搜索John是否在其中。

如果你只想数数:

SELECT COUNT(DISTINCT gameID) as numberofmatches FROM game_table WHERE CONCAT_WS(',', player1, player2, player3) LIKE '%,John,%' OR CONCAT_WS(',', player1, player2, player3) LIKE 'John,%' OR CONCAT_WS(',', player1, player2, player3) LIKE '%,John'

或者,如果你想要一个所有球员的名单:

(SELECT DISTINCT player1 AS player FROM game_table) UNION
(SELECT DISTINCT player2 AS player FROM game_table) UNION
(SELECT DISTINCT player3 AS player  FROM game_table)
ORDER BY player

你也可以将它与前一个结合起来,这给了我你想要的东西(我想):

SELECT player,count(distinct gameID) as numberofgames FROM game_table t1 JOIN ((SELECT DISTINCT player1 AS player FROM game_table) UNION (SELECT DISTINCT player2 AS player FROM game_table) UNION (SELECT DISTINCT player3 AS player  FROM game_table) ORDER BY player) t2 WHERE t2.player=t1.player1 OR t2.player=t1.player2 OR t2.player=t1.player3 GROUP by t2.player

这将返回一个表格,其中包含所有不同玩家的名字,包括他们玩过的游戏数量!

如果您只想选择某个人(John),请执行以下操作:

SELECT player,count(distinct gameID) as numberofgames FROM game_table t1 JOIN ((SELECT DISTINCT player1 AS player FROM game_table) UNION (SELECT DISTINCT player2 AS player FROM game_table) UNION (SELECT DISTINCT player3 AS player  FROM game_table) ORDER BY player) t2 WHERE (t2.player=t1.player1 OR t2.player=t1.player2 OR t2.player=t1.player3) AND t2.player='John' GROUP by t2.player

答案 1 :(得分:0)

您可以使用' IN'条款如:

$playerarray = array{'Derek','John','Gordon','Richard','Jim','Chance',....};
$sql = mysqli_query("SELECT * from game_table WHERE player1 IN (" . $value . ") OR player2 IN  (" . $value . ") OR player3 IN  (" . $value . ") OR player4 IN  (" . $value . ")");

另外,不要使用mysql,而是使用mysqli函数,因为第一个是被删除的。

或者,或者更确切地说,如果有很多玩家(意思是:很多列),你最好更改数据库的设计。规范化应该会使事情变得更容易。