2017-05-31 43 views
0

我擁有一個數據庫,其中包含一個比賽ID的數據庫。現在我希望沒有超過4支球隊以1 poule(id)。因此,如果4支球隊都在poule_id 1,它需要把他們在poule_id 2,如果有4 poule_id 2,他們需要去poule_id 3等計算數據庫中有多少個值相同,如果達到數量,則計數增加

poule table

我只選擇了poule_id是如此遠。

$sql = "SELECT poule_id FROM `tbl_teams` WHERE poule_id IS NOT NULL"; 
    $stmt = $this->db->prepare($sql); 
    $stmt->execute(); 
    $teams = $stmt->fetchAll(PDO::FETCH_ASSOC); 

    echo "<pre>"; 
    var_dump($teams); 

這讓我:

array(9) { 
    [0]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "1" 
    } 
    [1]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "1" 
    } 
    [2]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [3]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [4]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [5]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [6]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [7]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
    [8]=> 
    array(1) { 
    ["poule_id"]=> 
    string(1) "0" 
    } 
} 

現在我堅持,因爲我無法找到如何計算有多少球隊有在poule_id 1

對不起,我正在擦洗。 在此先感謝

+1

您需要使用COUNT()或者if(condition)> = X'。許多方法來做到這一點。可能添加一個GROUP BY。 –

回答

0

只要您插入邏輯是一樣的,你可以使用類似:

select if(
    exists(select max(poule_id) from tbl_teams group by poule_id having count(poule_id) < 4), 
    max(poule_id), 
    max(poule_id) +1 
) use_id 
from tbl_teams; 

得到你應該使用(如化名use_id)爲您的下插入poule_id。只要你只使用這個代碼來獲得你的下一個ID你應該沒問題。當然,請在您的特定用例中進行測試,以確保其符合您的預期。

+0

我應該在空表上添加這個返回'null',所以你可能需要測試你的第一個條目。 – siloko

相關問題