[英]Use IF/CASE statement to find if a substring exist in a string in MYSQL
I have a column which has a list of products in each row.我有一列,每行都有一个产品列表。 eg:例如:
I want to make a new column for each of the product, which will have a value of 1 or 0 depending on if that product exists in that row.我想为每个产品创建一个新列,根据该产品是否存在于该行中,该列的值为 1 或 0。
I'm using the following code right now:我现在正在使用以下代码:
select
*,
CASE WHEN product_name LIKE '%bat%' THEN 1 else 0 END AS bat,
CASE WHEN product_name LIKE '%gloves%' THEN 1 else 0 END AS gloves
from products
It does not work.这是行不通的。 Kindly help请帮忙
You can use handy MysQL function find_in_set()
to check if a value belongs to a comma-separated list:您可以使用方便的 MySQL 函数find_in_set()
来检查值是否属于逗号分隔列表:
select
p.*,
find_in_set('bat', product_name) > 0 bat
find_in_set('gloves', product_name) > 0 gloves
from products p
If the value is found in the CSV list, find_in_set()
returns a number between 1 and N that represents its position;如果在 CSV 列表中找到该值,则find_in_set()
返回一个 1 到 N 之间的数字,表示其位置; else it returns 0
(or null
if the searched CSV list is null
).否则返回0
(或null
,如果搜索到的CSV列表是null
)。 So basically, to check if a value belong to the CSV list, you just need to check if the value returned by find_in_set()
is strictly above 0
.所以基本上,要检查一个值是否属于 CSV 列表,您只需要检查find_in_set()
返回的值是否严格高于0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.