SQL计数按列的出现

时间:2019-07-09 07:49:07

标签: mysql sql count sql-like

经过一番研究,我没有找到我需要的东西,我想我会在这里问。我目前正在尝试为应用程序开发高级搜索模式,而我的工作陷于困境。也许你可以帮我。因此,假设我有下表:

ID | Name    | Surname
1  | John    | Mim
2  | Johnny  | Crazy
3  | Mike    | Something
4  | Milk    | Milk
5  | Peter   | IDontknow
6  | Mitch   | SomeName

然后在我的前端,有一个输入字段。该字段的输入将以这种方式通过查询:

SELECT name, surname FROM people WHERE name LIKE 'input%' OR surname LIKE 'input%'

现在可以说我的输入是“ Mi”,因此在“名称”列中将有3列匹配,在姓氏中有2列匹配。这就是我想要的。

计算出以下内容的计数:

Column  | Count
Name    | 3
Surname | 2

是否只有一种查询可以实现此目的?

到目前为止,我已经尝试过:
我实际上在数据库的本地主机上创建了上面的表,并尝试了不同的查询。尝试过SELECT count(name), count(surname),但两个计数都将输出3。因此,我什至不确定仅在一个查询中是否可行。

5 个答案:

答案 0 :(得分:1)

使用union all

SELECT 'name' as col, count(name) as cnt FROM people WHERE name LIKE 'input%' 
union all
SELECT 'surname', count(surname) FROM people WHERE  surname LIKE 'input%'

答案 1 :(得分:1)

使用案例进行自定义分组

SELECT (case when name  LIKE 'input%' then 'name'
          else 'surname' end) as Column, count(*) as cnt
    FROM people WHERE name LIKE 'input%' OR surname LIKE 'input%'
    group by Column

答案 2 :(得分:1)

尝试一下:

SELECT "Name" as Column, count(*) as Count FROM people WHERE name LIKE 'mi%'
UNION
SELECT "Surname" as Column, count(*) as Count FROM people WHERE surname LIKE 'mi%'

答案 3 :(得分:0)

在Mysql中,布尔值被评估为1或0,因此您可以执行以下操作:

select 'Name' Column, sum(name LIKE 'input%') Count from people
union all
select 'Surname', sum(surname LIKE 'input%') from people

对于Mysql 8.0+,您可以避免使用CTE对表进行两次扫描:

with cte as (
  select 
    sum(name LIKE 'input%') namecounter, 
    sum(surname LIKE 'input%') surnamecounter
  from people
)
select 'Name' Column, namecounter Count from cte
union all
select 'Surname', surnamecounter from cte

答案 4 :(得分:0)

UNION[ ALL]表中没有people的解决方案:

SELECT
  CASE cj.x WHEN 1 THEN 'Name' ELSE 'Surname' END AS `Column`,
  CASE cj.x
    WHEN 1 THEN COUNT(CASE WHEN Name LIKE concat(@input, '%') THEN 1 end)
    ELSE COUNT(CASE WHEN Surname LIKE concat(@input, '%') THEN 1 END)
  END `Count`
FROM people CROSS JOIN (SELECT 1 AS x UNION ALL SELECT 2) AS cj
WHERE Name LIKE concat(@input, '%') OR Surname LIKE concat(@input, '%')
GROUP BY cj.x;

Mi输入的输出:

| Column  | Count |
+---------+-------+
| Name    |     3 |
| Surname |     2 |

使用SQL Fiddle在线进行测试。