我有两个表: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/