如何根据数据库外部计算的值对MySQL数据进行排序

时间:2018-02-19 12:34:41

标签: php mysql sql html5

我有2个MySQL表:民意调查和candidate.candidates表存储候选人的名称和他们竞争的职位,即候选人(candidate_name,Position)民意调查表存储用户在投票时进行的每次民意调查。民意调查表结构是民意调查(candidate_name,Position)。假设主席只有一个职位,候选人是3个; x,y和z。当用户投票支持x时,表轮询中的一行用值(x,主席)填充。假设有6个投票,表格看起来像这样。

|y | Chairman|
|x | Chairman|
|z | Chairman|
|x | Chairman|
|y | Chairman|
|x | Chairman|

从这张表中,我想显示其中的每个候选人以及在html表中获得的投票数。执行此操作的代码是

$cnameres=mysqli_query($conn,"SELECT candidate_name FROM candidates WHERE Position ='Chairperson'");

            while($cname = mysqli_fetch_array($cnameres))
            {

                $v = $cname['candidate_name'];

                //total votes for each candidate

                $cand_ballot_count = mysqli_fetch_array(mysqli_query($conn, "SELECT COUNT(Position) FROM polls WHERE Position ='Chairperson' and candidate = '$v'"));
                $y = $cand_ballot_count[0] ;        

            //echo candidate and votes

              echo "<tr align='left'>"; 
                echo"<td>" .$v ."</td>";
                echo"<td>". $y. "</td>";

            }

结果将是一个名为result table的html表,如下所示。

| y | 2 |
| x | 3 |
| z | 1 |

我的问题; 我如何对这些数据进行排序,以便它可以在结果表上回显,同时按照这样的降序排序。

| x | 3 |
| y | 2 |
| z | 1 |

记住要排序的值不在数据库中。它只是计算行的结果。

2 个答案:

答案 0 :(得分:1)

计算数据库中的行数。然后排序很简单:

SELECT c.candidate_name, COUNT(p.candidate_name) as num_votes
FROM candidate c LEFT JOIN
     polls p
     ON c.candidate_name = p.candidate_name
WHERE c.Position = 'Chairperson'
GROUP BY c.candidate_name
ORDER BY COUNT(*) DESC;

我不确定join是否必要。您在两个表格中都冗余position_nameposition

答案 1 :(得分:1)

您可以SELECT c.candidate_name, count(*) AS votes FROM candidates c JOIN polls p ON c.candidate_name = p.candidate_name WHERE c.Position = 'Chairperson' GROUP BY c.candidate_name ORDER BY votes DESC; 将2个查询转换为下面的

$sql = "
SELECT c.candidate_name, count(*) AS votes
FROM candidates c 
JOIN polls p ON c.candidate_name = p.candidate_name
WHERE c.Position = 'Chairperson'
GROUP BY c.candidate_name
ORDER BY votes DESC;
";

$cnameres = mysqli_query($conn, $sql);

while($cname = mysqli_fetch_array($cnameres))
{

    $v = $cname['candidate_name'];

    //total votes for each candidate
    $y = $cname['votes'];

    echo "<tr align='left'>"; 
    echo"<td>" .$v ."</td>";
    echo"<td>". $y. "</td>";
    echo "<tr/>";
}

这是更新的代码剪辑

The documentation should be able to present mathematical-functions as well as possible graphics and if possible have a help-menu. Portability (html, pdf etc. would also be of interest).