如果投票为0,则投票结果查询未获得候选人

时间:2016-05-06 19:16:27

标签: php mysql codeigniter

我将在这里提出我的问题:

我有2个名为“Thesis”和“Votes”的表。表“论文”有两列,即:

  • ID
  • thesis_title

表“table Votes”包含以下列

  • ID
  • thesis_title
  • student_num

这是我的假数据

Thesis table
ID    thesis_title 
1     Online portal for FGC 
2     Reservation System 
3     Restaurant System 

table Votes 
ID    thesis_title           student_num
1     Online portal for Fgc  201311357
2     Reservation System     201311358
3     Online portal for FGC  201311359

我的输出是这样的:

thesis_title           votes
Online portal for fgc   2 
Reservation system      1
<no restaurant system>

期望的结果必须是

thesis_title           votes
Online portal for fgc   2 
Reservation system      1
Restaurant system       0

这是我的最新查询

$this->db->select('thesis.thesis_title,count(votes.thesis_title) as votes')
->from('thesis')->join('votes','thesis.thesis_title= votes.thesis_title','left')->group_by('votes.thesis_title');

2 个答案:

答案 0 :(得分:0)

如果我将您的php查询转换为SQL脚本,我可以生成正确的输出。

SELECT a.thesis_title, COUNT(b.thesis_title) AS votes FROM thesis a INNER JOIN votes b ON a.thesis_title = b.thesis_title GROUP BY b.thesis_title ORDER BY votes DESC;

如果您使用INNER JOIN,则不会出现餐厅系统投票,因为它会检查两列中的匹配记录。

您是否尝试过直接在数据库中查询?

答案 1 :(得分:0)

首先,你有一个糟糕的实体关系模型,因为你需要在你的投票表中使用一个外键,并使用id(论文)与这个外键(投票)进行连接。 最佳表格结构

Thesis                  Votes 
id                      id
thesis_title            thesis_fk
                        student_num
CI中的

查询

$query = $this->db->select('t.id, t.thesis_title, v.id as id2, v.student_num')
->from('Thesis t')
->join('Votes v', 't.id = c.thesis_fk', 'right');

return $query->result();
相关问题