mysql - 如何在codeigniter mysql中合并两个相同的行并显示不同的id行

标签 mysql codeigniter

我的 table 是这样的

 id ,  user_id , product_id , product_name , sub_name , status
  1 ,     1    ,    001     ,    name1     ,  sub1,       1
  2 ,     1    ,    001     ,    name1     ,  sub2,       1
  3 ,     1    ,    002     ,    name2     ,  sub3,       1    

我想在我的 View 页面中显示我的结果

 id , user_id , product_id , product_name , sub_name , status
  1 ,  1      ,  001     ,    name1     ,  sub1,       1
  3 ,  1      ,  002     ,    name2     ,  sub3,       1    

我的Sql查询

$data['product'] = $this->db->group_by('product_id')
            ->where(array('user_id' => $id, 'product_id' => $product_id))->get('sr_shortserials')->result();

但我就是这样

 id , user_id , product_id , product_name , sub_name , status
  3 ,  1      ,  002     ,    name2     ,  sub3,       1    

这个可以,但我想要 id 1 和 3

最佳答案

我假设您想要显示表中具有最早的 sub_name 字段值的所有产品。

最好的方法是重组您的数据并将 sub_name 字段分离到其单独的表中,因为您当前的数据结构在正常形式阶梯上并不是太高。

但是查询的主要逻辑并不真正依赖于 sub_name 是否是不同的表。您需要获取每个产品的最小 id(如果 sub_names 位于不同的表中,则为最小 sub_name id)并连接回主表(单独的 sub_names 表)以获得正确的详细信息。

select t1.*
from yourtable t1
inner join 
     (select user_id, product_id, min(id) as minid
      from yourtable
      group by user_id, product_id) t2 on t1.id=t2.minid

关于mysql - 如何在codeigniter mysql中合并两个相同的行并显示不同的id行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738066/

相关文章:

mysql - ActiveRecord 关联 : am I doing it right?

java - 如何在android 的listview 中显示来自mySQL 的数据?

php - 在 Codeigniter 应用程序中获取查询的行数

php - 将 Codeigniter 购物车数据插入数据库

php - 消息 : Undefined Variable userid , 工作区 ID

php - 如何在动态生成的 jQuery UI 选项卡上避免 FOUC

php - 如何避免多对多查询中的 "Using temporary"?

PHP MySQL curdate() 函数

mysql - 无法从表中删除任何行

php - 如何在codeIgniter中定义全局变量(值)