MYSQL:像子一样有趣

时间:2014-01-23 18:28:19

标签: php mysql sql

大家好我想知道如何在输出总成员上实现

这是查询

SELECT 
     field1,
     field2,
     (select count(*) 
       from table2 as t2 
       where t2.field5 LIKE '%' + t1.field2 + '%') as total_row 
FROM table1 as t1 ORDER BY total_row DESC

我想知道如何嵌入类似的语句,因为field5有一个或多个数据用逗号分隔为字符串

离。 field5有“猫,狗,老鼠”

所以field2正在寻找类似“狗”的总行

希望你能帮助我。

2 个答案:

答案 0 :(得分:0)

假设逗号后面没有空格,你需要做这样的事情:

select field1, field2, (
        select count(*)
        from table2 as t2
        where t2.field5 = t1.field2
            or t2.field5 like t1.field2 + ',%'
            or t2.field5 like '%,' + t1.field2 + ',%'
            or t2.field5 like '%,' + t1.field2
        ) as total_row
from table1 as t1
order by total_row desc

答案 1 :(得分:0)

在每个字段的正面和背面连接逗号:

SELECT field1
      ,field2
      ,( SELECT COUNT(*) 
         FROM table2 as t2 
         WHERE ','+t2.field5+',' LIKE '%,' + t1.field2 + ',%') as total_row 
FROM table1 as t1 ORDER BY total_row DESC

不确定上述内容是否适用于MySQL,可能需要CONCAT()

SELECT field1
      ,field2
      ,( SELECT COUNT(*) 
         FROM table2 as t2 
         WHERE CONCAT(',',t2.field5,',') LIKE CONCAT('%,',t1.field2,',%') as total_row 
FROM table1 as t1 ORDER BY total_row DESC