简体   繁体   中英

select comma separated data in MySQL

I want to select comma seperated data in query but i have some problems. The page have a categories list and uniq id. And the categories link like this;

<a href="index.php?page=categories&cat=1">Books</a>

I'm catching with $_GET "cat" id and listing matching users.

My problem when click cat=1, its listing all the user categories have 1 in it. Like id 1 and 11 and 15.

This is the my user table and his selected categories.

| User           | Categories | 
+----------------+------------+
| Jhon Doe       | 1,5,11     |

This is the query;

  $catid=$_GET['cat'];
  $list=$db->query("
  SELECT * FROM users 
  WHERE categories
  LIKE '%$catid%'")->fetchAll(PDO::FETCH_ASSOC);

It is almost always a bad idea to put lists of values in a field in SQL; this is no exception. Since your list is formatted nicely, you just have to take advantage of that... keep in mind this query will be extremely slow on anything but very small databases.

WHERE categories = '$catid'  -- only item
   OR categories LIKE '$catid,%' -- first item
   OR categories LIKE '%,$catid' -- last item
   OR categories LIKE '%,$catid,%' -- somewhere in the middle
;

Edit: Corrected above for actual list format; and as tadman said in the comment, FIND_IN_SET() is more succinct when your format is accepted by it (which this one is)... it is good to keep in mind that FIND_IN_SET() could be doing something similarly expensive behind the scenes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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