2016-11-19 27 views
0

相當簡單但卻掙扎着,我有一個表中有一列叫做'隊',其中一些行有多個隊,並且逗號分開,所以一個人可能有team1, team2另一個可能有team2,team3,team4從具有csv mysql的列中選擇數據

我想要做的是執行SELECT查詢,以便如果一個人有team1,另一個人有team1,它會輸出它們,儘管該列中有其他團隊。

這裏是我的查詢的基礎上的樣子:

$sql = "SELECT * FROM respondant_data WHERE respondant_team = 'Central Team'"; 
$result = $conn->query($sql); 

if($result->num_rows > 0){ 
    while($row = $result->fetch_assoc()){ 
     echo $row["respondant_firstname"]; 
     echo $row["respondant_lastname"]; 
     echo $row["respondant_team"]; 
     echo '<br>';   
    } 
} else{ 
    echo 'no results'; 
} 

正如你可以猜到它沒有返回值回我,因爲有「中央隊」所有用戶在其列有其他球隊了。

**更新**

所以按照下面的建議我已經進行了更新我的查詢:

$sql = "SELECT * FROM respondant_data WHERE FIND_IN_SET('Central Team', respondant_team) > 0"; 

所以它並返回一些數據,但不是全部,所以它返回的人列中的單個值仍然存在。

+2

你應該改變你的餐桌設計。它沒有正常化。切勿將多個值存儲在單個列中! –

+0

我遇到的問題是,我的客戶端通過CSV加載了這些數據,由於他們不願意更改他們的數據格式,所以我認真限制了這些數據。 – PhpDude

+0

然後查看一下'find_in_set()' –

回答

0
This solution provides you an case-insensitiv text search and prints every Member who is in team 1: 



$YOURNEEDLE = 'team 1'; 
       $sql = "SELECT * FROM respondant_data WHERE respondant_team = 'Central Team'"; 
       $result = $conn->query($sql); 
       if($result->num_rows > 0){ 
        while($row = $result->fetch_assoc()){ 
         if(stristr($row["respondant_team"],$YOURNEEDLE)) { 
          echo $row["respondant_firstname"]; 
          echo $row["respondant_lastname"]; 
          echo $row["respondant_team"]; 
          echo '<br>'; 
         } 
        } 
       } else{ 
        echo 'no results'; 
       } 

有很多waysd解決你的問題,另一個上:

  $needle = 'team 1'; 
      $sql = "SELECT * FROM respondant_data WHERE respondant_team = 'Central Team'"; 
      $result = $conn->query($sql); 
      if($result->num_rows > 0){ 
       while($row = $result->fetch_assoc()){ 
       $arrayTeams =  explode(', ',$row["respondant_team"]); 
        if(in_array($needle, $arrayTeams)) { 
         echo $row["respondant_firstname"]; 
         echo $row["respondant_lastname"]; 
         echo $row["respondant_team"]; 
         echo '<br>'; 
        } 
       } 
      } else{ 
       echo 'no results'; 
      } 
+0

爲什麼我收到了投票?請告訴最新的錯誤?否則我不能幫你? –

-1

不是最好的,但應該工作

SELECT * FROM respondant_data WHERE respondant_team RLIKE 'Central Team(?:,|$)' 

在PHP因此,建立這樣的查詢

$sql = 'SELECT * FROM respondant_data WHERE respondant_team RLIKE \''.$yourteamname.'(?:,|$)\'';