我的选择查询返回3行的相同数据

时间:2017-02-11 08:48:33

标签: php mysql json

我获得了第1,第2和第3的相同值。然后下一行给出了应该在第一行中假设的第二列中的结果。

<?php  
 require "db.php"; 
 $sql = "
SELECT e_name
     , IF(t_rank = 1, a_shortcut, a_shortcut) AS 1st
     , IF(t_rank = 1, a_shortcut, a_shortcut) AS 2nd
     , IF(t_rank = 3, a_shortcut, a_shortcut) AS 3rd    
  FROM team t
  JOIN event e
    ON t.EID = e.EID
";                         

 $con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name); 

$result = mysqli_query($con,$sql);


 $response = array();

while($row=mysqli_fetch_array($result))
{
array_push($response, array("e_name"=>$row[0],"1st"=>$row[1], 
"2nd"=>$row[2], "3rd"=>$row[3]));

} 
echo json_encode (array("nresults"=>$response));



mysqli_close($con);

?>

我的预期输出是

实施例。 Shortcut has a, b, c and they have rank a =1 b =2 c =3;

然后1st = a, 2nd = b, 3rd = c;

我得到的是什么

1st = a, 2nd = a, 3rd = a;

然后下一行显示

1st = b, 2nd = b, 3rd = b;

2 个答案:

答案 0 :(得分:1)

$sql = "select e_name
 , IF(t_rank = 1,'A',NULL) AS 1st
 , IF(t_rank = 2,'B',NULL) AS 2nd
 , IF(t_rank = 3,'C',NULL) as 3rd    
 from team t
join event e on t.EID = e.EID";          

这将返回A,B,C格式的等级..当条件匹配时,它将转换为A,B,C格式

答案 1 :(得分:0)

我认为您需要更改您的查询,如下所示:

$ sql =&#34;当t_rank = 1时选择e_name,CASE t_rank然后当t_rank = 2时选择a_shortcut然后当t_rank = 3时选择b_shortcut然后选择c_shortcut END作为team.EID = event.EID&#上团队内部加入事件的排名34 ;;

然后使用排名字段。 从team.EID = event.EID&#34 ;;上的团队内部联接事件中结束为matching_tag