Pergunta

I have a table which stores ID's in a comma separated string as follows:

field_id_13
------------
1234,5266,3678,4733,7372,5766,2578

and I'm using the following Active Record Construct (CI), to pull out the data:

$this->db->select("*")
    ->from("channel_data d")
    ->join("channel_titles t","t.entry_id=d.entry_id")
    ->where("d.field_id_13 LIKE '%".$id."%'")
    ->where("t.status","open")
    ->get();

The problem is that, sometimes on my search, the ID of '266' will be returned, therefore - because of my % surrounding the clause are returning a result matching against '5266'.

Whats the alternative here to make sure it only returns the correct ID/Rows?

Hopefully this makes sense.

Foi útil?

Solução

You have to use FIND_IN_SET in where condition

$this->db->where("FIND_IN_SET('$id',d.field_id_13 ) !=", 0);

Outras dicas

The simplest way, if not the most elegant, would be to add commas to the start and end of the values in the id field, and then search for the value surrounded by commas as well. In other words:

field_id_13
------------
,1234,5266,3678,4733,7372,5766,2578,

and:

$this->db->select("*")
    ->from("channel_data d")
    ->join("channel_titles t","t.entry_id=d.entry_id")
    ->where("d.field_id_13 LIKE '%,".$id.",%'")
    ->where("t.status","open")
    ->get();

SELECT * FROM your_table WHERE field_id_13 REGEXP ('^266,|,266,|266$')

Replace 266 with your target ID.

http://sqlfiddle.com/#!2/e6a74/1

The FIND_IN_SET solution looks more elegant, but this should work, too:

->where("d.field_id_13 REGEXP '[[:<:]]{$id}[[:>:]]'")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top