简体   繁体   English

没有主键的表上的CodeIgniter查询

[英]CodeIgniter Query on table without primary key

For some customers I am working on a project which is using a MySQL database. 对于某些客户,我正在研究一个使用MySQL数据库的项目。

I need to implement a search functionality which should be able to search in the database the devices with all the features selected. 我需要实现一个搜索功能,该功能应该能够在数据库中搜索具有所有选定功能的设备。 I am using CodeIgniter. 我正在使用CodeIgniter。 The problem is the structure of the table. 问题是表的结构。

I've found out that the table contains 2 columns: ID_D (the id of the device) and ID_F (the id of the feature). 我发现该表包含2列: ID_D (设备的ID)和ID_F (功能的ID)。 Basically the table doesn't contain any primary key (that's why I cannot execute any join at all). 基本上,该表不包含任何主键(这就是为什么我根本无法执行任何联接的原因)。

So, it's also possible that a device id can appear in 10 rows for each feature it has. 因此,对于具有的每个功能,设备ID也可能会出现在10行中。 When I execute the search, I have a list of the features ID and I should be able to read only the devices with all the features selected. 执行搜索时,我会列出功能部件ID,并且我应该只能读取选择了所有功能部件的设备。

if (isset($feature_array)) {
    foreach($feature_array as $key => $row) {
        $this->db->where('f_id',$row['f_id']); 
    }
}

Naturally, something like that won't work. 自然,类似的东西将不起作用。 Any ideas? 有任何想法吗?

I think this might solve your problem, in case the feature ids are unique and do not contain spaces. 我认为这可以解决您的问题,以防功能ID唯一且不包含空格。 In case they do contain spaces you should select a separator, that is not in the range of the feature ids. 如果它们确实包含空格,则应选择一个分隔符,该分隔符不在要素ID的范围内。

Basically the code uses the mySQL group_concat function to concatenate all feature ids and matches the created string by all searched features. 基本上,代码使用mySQL group_concat函数来连接所有功能ID,并通过所有搜索到的功能来匹配创建的字符串。 This finds all devices, that support at least the given set of features. 这将查找至少支持给定功能集的所有设备。

CI itself does not support that fucntion, so it is added by a workarround in the select method. CI本身不支持该功能,因此它是由工作环境在select方法中添加的。

Also this might be a bit load intensive if it is called on a large table. 同样,如果在大表上调用它,可能会占用大量的负载。 Maybe someone else got a faster solution? 也许其他人有更快的解决方案?

$this->db->select(['ID_D', 'GROUP_CONCAT(ID_F SEPARATOR \' \']) as id_f_concatenated']);
foreach($feature_array as $row) {
    $this->db->where("id_f_concatenated REGEXP '{$row['id_f']} | {$row['id_f']}|^{$row['id_f']}$'");
}
$this->db->group_by('ID_D');
$result = $this->db-get('tablename');

EDIT: Changed the LIKE to an REGEXP to make sure, that the feature id 112 is not matched by the id 12, without making the expression to complicated. 编辑:将“喜欢”更改为REGEXP,以确保功能ID 112与ID 12不匹配,而不会使表达式复杂。

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

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