【问题标题】:Altering a query to not duplicate data更改查询以不重复数据
【发布时间】:2014-08-09 16:08:35
【问题描述】:

在我的数据库中,我有 3 个表。

笑话:

CREATE TABLE IF NOT EXISTS `jokes` (
  `joke_id` int(11) NOT NULL AUTO_INCREMENT,
  `joke` varchar(1024) NOT NULL,
  `category_id` int(11) NOT NULL,
  `vote` int(255) NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

类别:

CREATE TABLE IF NOT EXISTS `category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(51) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

最后,评论:

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `comment` text NOT NULL,
  `joke_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

这个函数存储在我的读取控制器中,名称为 Joke,它从数据库中获取数据,然后将其发送到视图。

public function joke($joke_id = FALSE)
{
    if ($joke_id === FALSE) redirect('main'); //go to default controller

    $data['results'] = $this->comments_m->getComments($joke_id, $this->uri->segment(2));

    $this->load->view('template/header');
    $this->load->view('template/sidebar');
    $this->load->view('content/read', $data);
    $this->load->view('template/footer');

}

模型 (getjokes_m) 有一个名为 readJokes 的函数,它获取笑话、joke_id、类别名称、投票、cmets。该函数用于读取数据库中的特定笑话。

function readJokes($joke_id)
{

    $query = $this->db->query("SELECT c.name, j.*, co.* FROM jokes j LEFT JOIN category c ON c.category_id = j.category_id LEFT JOIN comments co ON co.joke_id = j.joke_id WHERE j.joke_id =  '$joke_id'") or die("No results found" );

    //displays the results
    return $query->result();

}

上面的查询是问题所在。目前,它返回笑话的次数与评论的笑话一样多。即如果笑话有 6 个 cmets,则该笑话将显示 6 次(不知道为什么)。任何更改此查询的帮助,只显示一次笑话,以及笑话的所有 cmets,将不胜感激。

【问题讨论】:

  • 在您返回所有“重复项”时阅读,并过滤它们以仅在您的代码中显示一次

标签: php mysql sql codeigniter join


【解决方案1】:

您想要一个 group bygroup_concat() 用于 cmets:

SELECT c.name, j.*, group_concat(co.comment separator '|') as comments
FROM jokes j LEFT JOIN
     category c
     ON c.category_id = j.category_id LEFT JOIN
     comments co
     ON co.joke_id = j.joke_id
WHERE j.joke_id =  '$joke_id'
GROUP BY j.joke_id;

实际上group by 在这里并不是绝对需要的,除非你想获得不止一个笑话的结果。

【讨论】:

  • 是的,group by 并不是我真正需要的,我需要能够为一个笑话抓取所有 cmets,而 group by 只是带来一个结果
  • @user3898892 。 . . group by 将所有 cmets 放在一个列中。
猜你喜欢
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 2015-03-09
  • 2019-05-14
相关资源
最近更新 更多