SQL - SELECT in string WHERE LIKE word1,word2,etc

时间:2017-06-09 12:55:51

标签: php mysql sql

I have a issu with my sql query. For each id in MySQL there is 1 or multiple tags. For example, id 1 have in his tags columns "110,2,3". id 2 have "3,1100". etc... Each number in tags string is a group. I need to SELECT users from specific group.

So I tried to use LIKE operator in SQL:

$query = $db->prepare(
    "SELECT * FROM USERS WHERE taglist LIKE :id_groups OR :id_groups2 OR :id_groups3"
    );

$query->execute([
  "id_groups"=> $id_groups.",%",
  "id_groups3"=> "%,".$id_groups,
  "id_groups2"=> "%,".$id_groups.",%"
  ]);

But isn't working as i wish. For example, if I replace $id_groups by "3", with the upper example. That will only SELECT the id 2, and not the id 1 even if id 1 have "3" in its tags.

And the last issu is how can i do when there is only 1 number in the string ? If I add another OR with "id_groups4"=> $id_groups that return me all the users even if they aren't in this group.

1 个答案:

答案 0 :(得分:1)

您需要为每个OR传递一个字段:

$query = $db->prepare("SELECT * FROM USERS WHERE taglist LIKE :id_groups OR taglist LIKE :id_groups2 OR taglist LIKE :id_groups3");

$query->execute([
  "id_groups"=> $id_groups.",%",
  "id_groups3"=> "%,".$id_groups,
  "id_groups2"=> "%,".$id_groups.",%"
  ]);

请注意,此用例并不涵盖单个标记,因为这要求每个标记都以逗号开头或后跟,您确实需要:

$query = $db->prepare("SELECT * FROM USERS WHERE taglist = :id_groups OR taglist LIKE :id_groups1 OR taglist LIKE :id_groups2 OR taglist LIKE :id_groups3");

$query->execute([
  "id_groups"=> $id_groups,
  "id_groups1"=> $id_groups.",%",
  "id_groups3"=> "%,".$id_groups,
  "id_groups2"=> "%,".$id_groups.",%"
  ]);