mysql select语句返回并不总是在同一列中的数据。

时间:2012-08-09 04:47:43

标签: php mysql

我有一个包含比赛名称和结果的Db。我正在尝试编写一个sql语句,它将确定所有特定的名称结果。问题是,根据比赛发生的地点,当地或在路上,结果在不同的栏目中。例如

    ____________________________________________________________________
    | home Runner | Road runner| road Outcome | home Outcome |   ID     |
    --------------------------------------------------------------------
    |    Jerry    |    Brian   |     323      |     350      |    1     |
    --------------------------------------------------------------------
    |   Brian     |    Jerry   |     259      |     265      |    2     |

正如你所看到的,如果我想为Brian取得结果,那就很难了,因为他的结果可以在公路和主页之间切换。我以为我可以存储一个包含所有与brians匹配的id的数组,然后以某种方式返回结果,取决于brian位于(home,road)的列到目前为止我已经完成了以下操作,但是在底部被卡住了

    $getRunner = "select id from $db where homeRunner = brian union select id from $db where roadRunner = Brian" order by id asc;
    $result=mysql_query($getRunner);
    $id=array(); // this is to hold all the Id's that match
    while($row = mysql_fetch_array($result)){
        $id[]=$row['id'];
    }
    foreach ($id as $element){
        $getOutcome = "select roadOutcome from $db where roadRunner = brian and id =$element"; 
        $result2 = mysql_query($getOutcome);
        while($row2 = mysql_fetch_array($result2)){
            echo $row2['roadOutcome'];
            echo '<br />';
        }

我知道很多问题。如果可能的话,我想整合查询,更不用说让它工作了。我怎么能说“如果homeRunner = brian然后选择homeOutcome,否则选择roadOutcome,其中id = $ element”?

最终,我试图在数组中返回答案,以便我可以绘制它。我用PHP写这个。谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

SELECT 
  CASE 
    WHEN HomeRunner = 'Brian' THEN 'Home'
    ELSE 'Road'
  END OutcomeType,
  CASE 
    WHEN HomeRunner = 'Brian' THEN HomeOutcome
    ELSE RoadOutcome 
  END Outcome
FROM $db
WHERE HomeRunner = 'Brian' OR RoadRunner = 'Brian'

答案 1 :(得分:0)

您可以在单个查询中实现此目的:

 SELECT IF(homeRunner = 'Brian', homeOutcome, road_Outcum) AS outcum
 FROM table_name
 WHERE (homeRunner = 'Brian' OR roadRunner = 'Brian');

答案 2 :(得分:0)

试试这个:

$getOutcome = "SELECT CASE 'BRIAN' 
               WHEN homeRunner THEN homeOutcome
               WHEN roadRunner THEN roadOutcome
               END FROM $db WHERE id =$element";
$result2 = mysql_query($getOutcome);
$outcome = mysql_fetch_row($getOutcome);
echo $outcome[0]; // Final Output!