PHP MySQL短查询关联代码

时间:2016-12-07 14:29:21

标签: javascript php html css mysql

我需要查询和关联这样的许多查询

<?php 
$datacenter=mysqli_connect('localhost','user','pass','db');

数据库连接,现在我们计算投票选项1和2和3的数量

 $r11=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total1` 
FROM `votes` WHERE `firstvote` = '1' ");
    $r11r=mysqli_fetch_assoc($r11);


    $r12=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total2` 
FROM `votes` WHERE `firstvote` = '2'");
    $r12r=mysqli_fetch_assoc($r12);

    $r13=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total3` 
FROM `votes` WHERE `firstvote` = '3'");
    $r13r=mysqli_fetch_assoc($r13);
    ?>

现在我们回显结果以显示有多少投票选项1,2和3

<?php echo number_format($r11r['total1'],0,',','.'); ?>
<? php echo number_format($r12r['total2'],0,',','.'); ?>
<? php echo number_format($r13r['total3'],0,',','.'); ?>

有没有办法让这段代码更短?我是PHP的新手

4 个答案:

答案 0 :(得分:2)

您可以在查询中使用GROUP BY

SELECT 
  firstvote,
  COUNT(*) AS count
FROM votes
GROUP BY firstvote

您可以使用此值覆盖所有唯一firstvote和行计数。 如果您只想为此firstvote选择值,则可以使用此查询:

SELECT 
  firstvote,
  COUNT(*) AS count
FROM votes
WHERE firstvote IN (1, 2, 3)
GROUP BY firstvote

要按计数排序值,您可以使用ORDER BY

SELECT 
  firstvote,
  COUNT(*) AS count
FROM votes
GROUP BY firstvote
ORDER BY count DESC
LIMIT 3

DESC首先意味着更大。

答案 1 :(得分:0)

foreach(array(1,2,3) as $firstvote){
  $res=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total` 
                                  FROM `votes` WHERE `firstvote` = '$firstvote' ");
  $r[$firstvote]=mysqli_fetch_assoc($res);
 }

foreach($r as $set){
  echo number_format($set['total'],0,',','.'); 
}

仅限高票:

$r['total']=0;
foreach(array(1,2,3) as $firstvote){
  $res=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total` 
                                  FROM `votes` WHERE `firstvote` = '$firstvote' ");
  $tmp=mysqli_fetch_assoc($res);
  $r=max($tmp['total'],$r['total']);
 }


 echo number_format($r,0,',','.'); 

因为我现在不想做你真正想做的事情,所以这是一个只获得所有结果的最高价值的解决方案。但是你应该在你的SQL查询中执行此操作。添加ORDER BY total LIMIT 1

之类的内容

答案 2 :(得分:0)

您可以使用CASE语法并在一个查询中完成所有操作

$sql = "SELECT
            SUM(CASE WHEN `firstvote` = 1 THEN 1 ELSE 0 END) AS total1,
            SUM(CASE WHEN `firstvote` = 2 THEN 1 ELSE 0 END) AS total2,
            SUM(CASE WHEN `firstvote` = 3 THEN 1 ELSE 0 END) AS total3
        FROM `votes`";

$res = mysqli_query($datacenter, $sql);
$row = mysqli_fetch_assoc($res);

echo number_format($row['total1'],0,',','.');
echo number_format($row['total2'],0,',','.');
echo number_format($row['total3'],0,',','.');

这将在单个结果行中返回名为total1 total2total3的3列

答案 3 :(得分:0)

$result = mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total1` FROM `votes` WHERE `firstvote` in ('1','2','3') GROUP BY firstvote");

while ($row = mysqli_fetch_assoc($result)) {
    echo number_format($row['total1'], 0, ',', '.');
}