1

我有一个名为“Offres”的 sql 表
,该表中有一个名为“regions”的列,其中包含数组 (value1, value2, value3,...)
row1 :"35,2,15,69,98"
row2 :"7 ,9,15,5,69"
row3 :"7,3,45,5,6"
我如何搜索同时具有多个值的行
exp :我想搜索其中包含 15,69 的
行结果应该显示 row1 和 row2
谢谢

在此处输入图像描述

4

5 回答 5

5

永远,永远,永远不要在一列中存储多个值!

正如你现在看到的,这只会导致问题。请首先像这样规范化您的数据库结构

Offers
id   region
1    35
1    2
1    15
...
2    7
2    9
2    15
...
于 2013-09-06T09:40:11.060 回答
0

如果您打算通过 SQL 搜索字段,请将其存储为多行并且不要序列化它。

如果出于某些原因,您必须提取每一行,对其进行反序列化(对于您的情况,使用 withexplode()并单独匹配它,这会占用大量处理能力。

于 2013-09-06T09:44:41.090 回答
0

您可以使用 FIND_IN_SET() 在此类列表中搜索元素。如果您需要在行中查找多个条目,则需要多个选择。

但是:好的数据库结构可以避免这一切,并且每行只有一个条目而不是列表

于 2013-09-06T09:45:22.447 回答
-1

For the sake of completeness I am posting this as an answer, too, so it does not get lost in the huge discussion in the comments ;)

First of all, if you want to have multiple values in one column in SQL the set-column is the way to go. See for example here and here. But if you absolutely cannot get around having multiple values in one column and you can guarantee, that they will always occur in the same pattern (comma-separated, no spaces), then you can search for rows that contain 2 specific such values you can do it like this (according to your example)

SELECT * FROM Offres WHERE
  (
      regions = '15' /*value is the only one in that row, obviously this is not necessary if you look for 2 values at once, but if you would only look for one value at once you MUST include it ;)*/
    OR regions LIKE '%,15' /*value is the last value in that row*/
    OR regions LIKE '15,%' /*value is the first value in that row*/
    OR regions LIKE '%,15,%' /*value is a value somewhere in between other values in that row*/
  )
  AND
  (
      regions = '69' /*value is the only one in that row, obviously this is not necessary if you look for 2 values at once, but if you would only look for one value at once you MUST include it ;)*/
    OR regions LIKE '%,69' /*value is the last value in that row*/
    OR regions LIKE '69,%' /*value is the first value in that row*/
    OR regions LIKE '%,69,%' /*value is a value somewhere in between other values in that row*/
  )

You can also try that out in this fiddle.

于 2013-09-06T11:48:43.380 回答
-2

对于 exp :我想搜索其中包含 15,69 的行


如果您可以在值之前和之后添加空格,那么检查小提琴可能很容易

喜欢

row1 :' 690 , 6969 , 069 , 69069 '
row2 :' 69 , 69 , 69 , 69 , 69 '
row3 :' 6969 , 69 , 69069 '
row4 :' 069 , 69069 '
row5 :' 69 '

    SELECT * FROM Offres WHERE regions LIKE regions LIKE '% 69 %';
于 2013-09-06T09:47:25.473 回答