简体   繁体   English

在MySQL中选择逗号分隔的数据

[英]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. 该页面具有类别列表和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. 我正在捕捉$_GET “ cat” id并列出匹配的用户。

My problem when click cat=1, its listing all the user categories have 1 in it. 单击cat = 1时出现我的问题,它列出的所有用户类别都包含1。 Like id 1 and 11 and 15. 像ID 1、11和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; 将值列表放在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. 正如塔德曼(Tadman)在评论中说的那样,当您的格式被接受时,FIND_IN_SET()更加简洁(这就是事实)...请记住,FIND_IN_SET()可能在幕后做了类似的昂贵工作。

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

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