简体   繁体   English

如果条件在mySQL查询中与Codeigniter中的join

[英]If condition in mySQL query with join in Codeigniter

Good Day! 美好的一天!

Is it possible to apply if condition in the query in codeigniter: model ? codeigniter: model中的query if condition是否可以应用? I have this query in Model : 我在Model有此查询:

function activity($id) {        
        $this->db->select('a.ID, a.activityID, r.roleName');
        $this->db->from('activity a');
        $this->db->join('role r', 'r.ID = a.activityID');
        $this->db->where('a.ID', $id);
        $query = $this->db->get();

        return $query->result_array();
    }

And in my view I want to show the ID and activityID from table activity and also the counter part roleName (from table role) of activityID . 在我看来,我想显示ID and activityID from table activityID and activityID from table activity的对应角色roleName (from table role) of activityID But the tricky part is that the value in activityID is not just a simple INT , like this: 但棘手的是, activityID中的值不仅仅是一个简单的INT ,如下所示:

ID  ActivityID
1   5,7,9
2   2,4
3   
4   10
5   1,6

So I'm thinking to use if condition in the query, like if the activityID value not contains comma (,) it will use join like this: $this->db->join('role r', 'r.ID = a.activityID'); 因此,我正在考虑在查询中使用if条件,例如,如果activityID值不包含逗号(,),它将使用以下$this->db->join('role r', 'r.ID = a.activityID');$this->db->join('role r', 'r.ID = a.activityID'); then get the r.roleName . 然后获取r.roleName Example: 例:

ID  ActivityID  Role Name
4   10          Basketball

But if contains comma (,), it will explode by comma (,) then join like this: $this->db->join('role r', 'r.ID = a.activityID'); 但是,如果包含逗号(,),它将被逗号(,) explode ,然后像这样加入: $this->db->join('role r', 'r.ID = a.activityID'); but it will output also by roleName with comma in between. 但它也将由roleName输出,中间用逗号隔开。 Example: 例:

ID  ActivityID  Role Name
1   5,7,9       Tennis,Football,Soccer
2   2,4         Volleyball,Chess

Can someone help me with this? 有人可以帮我弄这个吗? Thanks in advance. 提前致谢。

This is very bad idea to have comma separated ids in your column you should first normalize your structure other wise it will lead you more expensive problems,for now you use FIND_IN_SET() ,for having role names also as comma separated you can use GROUP_CONCAT 在列中用逗号分隔ID是一个非常糟糕的主意,您应该首先规范化结构,否则将导致更为昂贵的问题,因为现在您使用FIND_IN_SET() ,因为角色名称也以逗号分隔,您可以使用GROUP_CONCAT

Be ware of that fact it has a default limit of 1024 characters to concat but it can be increased which is defined in manual 请注意,默认情况下,concat的默认限制为1024个字符,但可以增加,这在手册中已定义

SELECT 
a.ID, 
GROUP_CONCAT(a.activityID) activityID,
GROUP_CONCAT(r.roleName) roleName
  FROM activity a
  LEFT JOIN `role` r ON(FIND_IN_SET(r.ID,a.activityID) > 0);
  WHERE a.ID = $id
  GROUP BY a.ID

For CI use query() function for above query 对于CI,请使用query()函数进行上述查询

Please first have a look at Database Normalization 请先看看数据库规范化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM