0

我有两个表: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 上只有一条记录。有什么解决方案吗?

4

2 回答 2

1

听起来你需要使用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
于 2013-03-29T18:49:34.780 回答
0

ok the final solution for this thing after 8 hours . by the end user post code entry , trim the post code off any spaces , and then str_replace the spaces to nothing , and then take off the last 3 letter / numbers of the string . and save it as an additional column along with the original postcode , now you will have post codes store like LS1 . LS11 , and instead of inner join using like , use = . this is i believe the only way out there.

see This link for more info

于 2013-03-30T03:38:34.080 回答