【问题标题】:get count number of values with comma seprated [duplicate]获取用逗号分隔的值的计数[重复]
【发布时间】:2020-06-30 16:57:55
【问题描述】:

我在 SQL 中有一个以逗号分隔的列表(即猫、狗、牛)的列,我需要仅使用 mysql 计算其中的猫、狗和牛的数量

id | Name
1  | dog,cat
2  | cow,cat
3  | dog,cat,cow

【问题讨论】:

  • 你不应该像这样在你的 MySQL 表中存储 CSV。

标签: mysql sql phpmyadmin


【解决方案1】:

您首先应该着手修复您的数据模型。您应该有一个单独的表来存储 id/name 关系,其中每个元组将存储在单独的行中,例如:

id    name
----------
1     dog
1     cat
2     cow
2     cat
3     dog
3     cat
3     cow

这将使您的查询更加简单和高效。

根据您当前的设置:如果值列表是固定的,您可以使用find_in_set() 和条件聚合:

select
    sum(find_in_set('cat', name) > 0) no_cats
    sum(find_in_set('cow', name) > 0) no_cows,
    sum(find_in_set('dog', name) > 0) no_dogs
from mytable

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2015-01-01
    • 2010-10-22
    • 1970-01-01
    • 2014-03-03
    • 2013-04-15
    • 2018-01-14
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多