Mysql 如何使用sql检查列表属性中的计数?
有一个名为productlist的attibute,其类型为list,包含许多产品 因此,我希望所有在productlist中只有一种产品的客户:Mysql 如何使用sql检查列表属性中的计数?,mysql,sql,hybris,Mysql,Sql,Hybris,有一个名为productlist的attibute,其类型为list,包含许多产品 因此,我希望所有在productlist中只有一种产品的客户: customer productlist xxxx 12345, yyyy 12345,67891, zzzz 101112,52693,89563, aaaa 12536 Expected Results : customer productlist xxxx 12345, aaaa 12536
customer productlist
xxxx 12345,
yyyy 12345,67891,
zzzz 101112,52693,89563,
aaaa 12536
Expected Results :
customer productlist
xxxx 12345,
aaaa 12536
任何帮助都将不胜感激。正如jarlh所说,如果可能,请尝试重新构建数据库 但为了在这种特定情况下提供帮助,可以使用用户定义的函数和charindex()执行一些操作,该函数将返回productlist列中出现的“,”的数目。这将中断执行,因为它必须为每一行执行一次,并对性能产生重大影响,但它将完成任务 查看示例数据,您需要检查第一次出现“,”之后是否有产品 试试这个例子:
DECLARE @TAble TABLE
(
customerName varchar(50),
productlist varchar(50)
)
INSERT INTO @table VALUES ('xxxx', '12345')
INSERT INTO @table VALUES('yyyy', '12345,67891')
INSERT INTO @table VALUES('zzzz', '101112,52693,89563')
INSERT INTO @table VALUES('aaaa', '12536')
SELECT * FROM (
select customerName,productlist,len(productlist)- len(replace(productlist,',','') )+1 as counts from @TAble
) AS t
WHERE t.counts=1
Output :
customerName productlist counts
xxxx 12345 1
aaaa 12536 1
使用
REPLACE
将原始字符串的长度与删除所有逗号的字符串的长度进行比较,并使用REGEXP
覆盖有尾随逗号的情况:
SELECT *
FROM table_name
WHERE length(productlist) - length(replace(productlist, ',', '')
- if(productlist REGEXP '.*, *$', 1, 0) /* Handles trailing commas */
= 0;
我曾在MySQL中尝试过这个方法,效果很好 试用
select customer,productlist from table_name
where instr(substr(productlist,1,length(productlist)-1),',')=0;
永远不要将数据存储为逗号分隔的项。这只会给你带来很多麻烦。@jarlh谢谢你的建议,但到目前为止,我还不可能这么做。我想从数据中获取列表。