【问题标题】:MYSQL select count two table left joinMYSQL 选择计数两个表左连接
【发布时间】:2020-12-07 02:39:10
【问题描述】:

我有两张桌子。 我想计算一个值在其他表中的次数。所以表“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

但我有一个错误的结果

【问题讨论】:

    标签: mysql sql join count subquery


    【解决方案1】:

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

    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
    

    【讨论】:

    • 嗨,谢谢,我在示例表中尝试过,它可以工作。所以我想在两个表中使用,第一个有 25 k 记录,第二个有 100k 记录......所以很慢,5分钟后我没有结果@GMB
    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2012-05-15
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2020-05-05
    相关资源
    最近更新 更多