MYSQL select 计数两个 table 左连接
MYSQL select count two table left join
我有两个table。
我想计算一个值在其他 table 中的次数。所以 table “sorgente” 的抄本在 table 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
我有两个table。 我想计算一个值在其他 table 中的次数。所以 table “sorgente” 的抄本在 table 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