Mysql查询代码


Mysql Query In codeigniter

这是我的mysql查询

$acountry = 1;
$this->db->where_in('varcountry', $acountry);
$val = $this->db->get('tblagencies')->result();

在数据库表中,varcountry字段是这样存储的:1,2,3,4,类型为varchar。表中的每一行都有多个国家,这就是使用varchar数据类型的原因。

这里我想选择在varcountry字段中具有$acountry值的表行。

我该怎么做呢?以上代码是正确的吗?

您为将逗号分隔的值1,2,3,4存储到varchar中选择了错误的数据类型,
您应该选择数据集的数据类型,或者将其规范化为单独的表,例如:-

create table country (id, name ...);
create table agencies_country ( agency_id, country_id);
insert into agencies_country (agency_id, country_id)
values (x,1), (x,2), (x,3), (x,4);
// meaning 1,2,3,4 = 4 rows
// grabbing result using inner join

使用set更容易,但通常的做法是规范化数据(这需要一些理解)。

我不喜欢codeigniter中的活动记录,
很容易使用(毫无疑问),
但是它不允许失去灵活性

我个人喜欢构造我自己的查询,
前提是您了解表模式(无论如何都必须了解)

使用这个查询…

$search_field = array('varcountry'=>$acountry)
$result = $this->db->get_where('tblagencies' , $search_field );
but in codeignator you can use your own queries like
$sql = "select * from tblagencies where varcountry like '%acountry%'";
$result = $this->db->query($sql);