簡體   English   中英

MySql逗號分隔值,使用Where子句獲取

[英]MySql Comma Separated Values , Fetch Using Where Clause

我必須獲取table的列,其中一列值用delimete逗號分隔,這是我的表結構

id  | name | categoryID
 1    a       1,2,4
 2    b       333 , 1 , 5 , 54
 3    c       1114414 , 2 , 3, 4, 5, 6 ,7
 4    d       2 , 4 , 5, 333, 7 , 8

Here is my query

Select * from tableA where find_in_set ('categoryID' , '1,7,8,333');

但是上面的查詢無法正常工作,它返回空行。

第1步:

我建議您更改架構。 名稱映射到許多類別

id,name,categoryId
1  a     1
2  a     2
3  a     4
4  b     1
5  b     5

第2步:

查找以下類別的所有名稱

Select distinct name,id,category_id from tableA where categoryId IN (1,7,8,333);
Select * from tableA where find_in_set (categoryID , '1,7,8,333')

如果您為categoryID傳遞值1,則'find_in_set'將正確返回該值。 但是您正在嘗試通過(1,2,4),(333,1,5,54)。 因此,它返回錯誤的值。

您對find_in_set函數的使用不正確。 以下內容可能會很有用,因為它描述了如何正確使用find_in_set函數。

在這里您可以找到: find_in_set

因此,使用它來查找字符串在逗號分隔列表中的位置,如下所示(請注意,它不區分大小寫):

select find_in_set('Z', 'a,b,z,0');

//將產生:3

您必須在find_in_set錯誤的地方使用OR。 用於

Select * from tableA where find_in_set ('1',categoryID) OR find_in_set ('7',categoryID);

不要在單引號中使用categoryID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM