dongzhi4239 2015-08-05 17:26
浏览 24
已采纳

如何通过分组两列来防止重复? MYSQL /笨

I have a predicament where I'm trying to make a facebook-style wall where you have the wall table, users table, wall post table and images table (for this scenario). To simplify the process, the image is posted in the images table, and an entry is made as a wall post. It groups by wall id but when comments are made, it repeats the wall post for every new comment. Essentially I just want ONE post per wall post.

MYSQL Query (Codeigniter):

    $this->db->select('*');
    $this->db->from('wall_posts AS p');
    $this->db->join('users AS k', 'p.wall_poster = k.user_id AND p.wall_owner = k.user_id', 'left');
    $this->db->group_by('p.wall_id');
    $this->db->where('p.wall_poster', $pid); // $pid = given user id
    $this->db->or_where('p.wall_owner', $pid);
    $this->db->order_by('p.wall_id', 'desc');
    $this->db->limit($lim); // $lim = limit number

    return $this->db->get();

Table example

    wall_id|owner_id|reference_id|wall_poster
    1      |0        |55         | 2
    2      |0        |30         | 1
    3      |0        |32         | 2
    4      |2        |19         | 3
    5      |0        |0          | 4
    6      |0        |0          | 2
    7      |0        |32         | 3
    8      |0        |18         | 4

Now, you can see that ID 3 and ID 7 has the same reference_id (image in this case), so later when the result is displayed, any posts referencing that image will be displayed multiple times instead of just once. I also have a column called post_type to help afterwards in the controller which determines if it's a normal post, comment, an image post, comment of an image etc...

Thanks ahead of time! This is bugging me to no end and I'd like to keep this as a single query if possible.

  • 写回答

1条回答 默认 最新

  • doukao2180 2015-08-05 18:11
    关注

    you could try select distinct, but you'd need to narrow it down to just that field. In other words, try something like this:

    Edited for codeigniter method for distinct()

    $this->db->distinct();
    $this->db->select ('reference_id');
    $this->db->from('wall_posts AS p');
    $this->db->join('users AS k', 'p.wall_poster = k.user_id AND p.wall_owner = k.user_id', 'left');
    $this->db->group_by('p.wall_id');
    $this->db->where('p.wall_poster', $pid); // $pid = given user id
    $this->db->or_where('p.wall_owner', $pid);
    $this->db->order_by('p.wall_id', 'desc');
    

    Alternately you could try:

    $this->db->select('DISTINCT(reference_id)');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路