簡體   English   中英

在不同的MySQL列中計數相同的值

[英]Count same values in different column mysql

我需要計算在同一ID的不同列中的相同值中成熟了多少次。我將嘗試通過一個示例進行說明: TABLE:

+-----+-----+-----+-----+-----+
|  id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
|  1  |  A  |  A  | B   |  B  | 
+-----+-----+-----+-----+-----+
|  2  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  3  |  B  |  B  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  4  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  5  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  6  |  B  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+

我需要知道“ B ”值對任何人(ID)重復多少次。

有可能做到這一點嗎? 結果

+-----+-----+-----+
|  id |  count B  |
+=====+=====+=====+
|  1  |     2     |
+-----+-----+-----+
|  2  |     0     |
+-----+-----+-----+
|  3  |     2     |
+-----+-----+-----+

我當時想使用函數“ SUM”,但我不知道如何僅顯示單個ID。 在此先感謝您,希望問題很清楚!

如果只有四列:

SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename

沒有31列

您可以通過兩種方式解決此問題:

  1. 對其他27列重復條件:)
  2. 規范化您的結構,以使每個值都依賴於id和代表日歷的數字值。

PHP方式

您還可以獲取所有列,然后讓PHP為您解決:

$res = $db->query('SELECT * FROM tablename');
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $id = $row['id'];
    unset($row['id']); // don't count the id column
    $count = count(array_keys($row, 'B', true));

    printf("ID %d: %d\n", $id, $count);
}

由於您似乎正在使用mysql_ *:

// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';

// In this loop we will construct our SELECT query using the columns returned 
// from the above query
while($row=mysql_fetch_array($sql)){
    if($row['Field']!='id'){
            $new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
    }
}

//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like: 
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1

$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
 echo 'ID - '.$row2['id']."<br>";
 echo 'Count - '.$row2['count']."<br>";
}

注意:

mysql_ *已過時 ,請考慮遷移到mysqli_ *

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM