php - mysql内连接计数问题

标签 php mysql

我有两个表:Table1 和 Table2。

表1:

log_id | postcode
1      |  LS11LS

表2:

region | postcode
Leeds     | LS1
Leeds     | LS11

当我使用以下查询时,

SELECT table2.region 'Region', 
       Count(table1.postcode) AS 'count' 
FROM   table1 
INNER JOIN table2 
   ON table1.postcode LIKE Concat(table2.postcode, '%') 

我明白

Region   |   count
Leeds    |    2

其中应该为 1,因为 Table1 上只有一条记录。有什么解决办法吗?

最佳答案

听起来您需要使用DISTINCT:

SELECT table2.region 'Region', 
    COUNT( DISTINCT table1.log_id )  as 'count' 
FROM table1 
    INNER JOIN table2 ON 
        table1.postcode LIKE CONCAT( table2.postcode,  '%' )

我用 log_id 替换了邮政编码,因为它可能是您的唯一列。

编辑:虽然我不太确定您在寻找什么,但这是使用子查询的替代方法:

SELECT Region, COUNT(1) as 'Count'
FROM Table1 T
    JOIN (
        SELECT DISTINCT T2.Region, T.PostCode
        FROM table1 T
            INNER JOIN table2 T2 ON 
                    T.postcode LIKE CONCAT( T2.postcode,  '%' )
    ) T2 ON T.PostCode = T2.PostCode

关于php - mysql内连接计数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709541/

相关文章:

php - 在 mysql 中加入并计算行值?

php - 交易错误后数据也被保存

php - iPhone表情插入MySQL却变成空值

php - SQL 使用 cast 而不是 int 字段

php - 如何在 cdbcriteria 中编写此连接查询?

mysql - sql请求-多值

php - cakephp 保存数组

MySQL 选择具有特定属性的计数行

php - 使用 JSON 或 XML 发送 JavaScript 数组?如何将其转换为 XML?

php - Mysql文本字段同时包含<p>和<img> : How to loop through just <img>?