首页 > 解决方案 > MYSQL 选择计数两个表左连接

问题描述

我有两张桌子。我想计算一个值在其他表中的次数。所以表“sorgente”的代码在表 contatore 中是不同的,因为我在代码前有后缀“BRANO-”。我尝试使用 LIKE,但它不起作用。

sorgente
| codice | nome  |
|   15   | mario |
|   16   | mary  |

contatore
| nome_evento |   data     |
| BRANO-15    | 2020-08-15 |
| BRANO-15    | 2020-08-16 |
| BRANO-16    | 2020-08-14 |

所以查询可能是

SELECT sorgente.codice, count(contatore.nome_evento)
FROM sorgente
JOIN contatore
WHERE contatore.nome_evento LIKE '%-'sorgente.codice

但我有错误的结果

标签: mysqlsqljoincountsubquery

解决方案


使用字符串连接。子查询似乎是一个自然的解决方案:

select
    s.codice,
    (
        select count(*) 
        from contatore c 
        where c.nome_evento = concat('BRANO-', s.codice) 
    ) no_matches_in_contatore
from sorgente s

但您也可以加入和聚合:

select s.codice, count(c.nome_evento) no_matches_in_contatore
from sorgente s
left join contatore c on c.nome_evento = concat('BRANO-', s.codice) 
group by s.codice

推荐阅读