mysql - 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
但我有错误的结果
解决方案
使用字符串连接。子查询似乎是一个自然的解决方案:
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
推荐阅读
- python - 如何运行 paramiko demo_server.py?
- makefile - 当存在无意的循环依赖时停止 Makefile
- python - 有没有办法绘制一个函数,它是 python 中具有 2 个变量的函数的部分导数?
- java - 如果java是传值,那为什么p1.age是25而不是22呢?请提供解释
- javascript - 如何修复从它生成的数组中翻转的 tilemap?
- javascript - 如何在 lodash debounce 中调用类方法?
- css - 试图将一个 background-size 属性设置为等于另一个
- javascript - 搜索数组未返回预期结果 - 它不断出现错误
- sitefinity - 来自操作方法的 sitefinity 更新视图
- javascript - 如何在 Mongoose/Node 中同时渲染多个变量?