【问题标题】:Re-writing several individual SQL query's into one [duplicate]将几个单独的 SQL 查询重写为一个 [重复]
【发布时间】:2020-10-05 14:47:13
【问题描述】:

我有一个数据库,我在其中显示来自表的不同列的行数,作为网站的统计信息。在纯文本中是这样的(英文翻译):

“目前,登记的问题有8616属于历史类别,6属于地理类别。 "

我的 PHP 脚本非常简单:

$question_query = mysqli_query($conn, 'SELECT Q_id FROM questions');  
$question_result = mysqli_num_rows($question_query);

$historie_query = mysqli_query($conn, "SELECT Q_id FROM questions WHERE category LIKE '%Historie%'");  
$historie_result = mysqli_num_rows($historie_query);

$geografi_query = mysqli_query($conn, "SELECT Q_id FROM questions WHERE category LIKE '%Geografi%'");  
$geografi_result = mysqli_num_rows($geografi_query);

echo '<h3>' . 'For øyeblikket er det ' . '<b>' . $question_result . '</b>' . ' spørsmål i databasen:' . '</h3>';
echo '<ul>' . '<li>' . '<b>' . $historie_result . '</b>' . ' historie-spørsmål.' . '</li>' ;
echo '<li>' . '<b>' . $geografi_result . '</b>' . ' geografi-spørsmål.' . '</li>' . '</ul>';

这很好用,但现在它只执行 3 个查询。未来,大概会有 10 到 15 个查询。

我尝试将它们合并为一个,但它只输出第一个查询:

$query =  "SELECT Q_id FROM questions"; 
        "SELECT Q_id FROM questions WHERE category LIKE '%Historie%'"; 
        "SELECT Q_id FROM questions WHERE category LIKE '%Geografi%'";

$result = mysqli_query ($conn, $query);
$count = mysqli_num_rows($result);

print_r ($count);

我认为 while 循环可能能够解决这个问题,但是当我将 print_r 替换为 while 循环时,对于不同的行数($question_count、$historie_count、$geografi_count),我得到一个未定义的变量错误:

while ($row = mysqli_fetch_assoc($result)) {
    $row[0] = $question_count;
    $row[1] = $historie_count;
    $row[2] = $geografi_count;

    print_r ($question_count . '</br>' . $historie_count . '</br>' . $geografi_count);

}

我怎样才能把它变成一个查询?而且,这是可取的,还是将查询分开更好?

提前致谢!

【问题讨论】:

标签: php mysql string count pivot


【解决方案1】:

使用条件聚合:

select 
    count(*) question_count, 
    sum(category like '%Historie%') historie_count, 
    sum(category like '%Geografi%') geografi_count
from questions 

【讨论】:

  • 这将是一个很好的解决方案!你是如何在 PHP 中做到这一点的?
  • 以上是一个普通的 sql 语句,因此您通常会在当前项目的结构中传递一个 sql 语句。也就是说,还可以考虑使用准备好的语句并参数化LIKE 条件
猜你喜欢
  • 1970-01-01
  • 2015-11-22
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2020-09-08
  • 1970-01-01
  • 2015-10-24
相关资源
最近更新 更多