I have two tables: Table1 and Table2.
Table1:
log_id | postcode
1 | LS11LS
Table2:
region | postcode
Leeds | LS1
Leeds | LS11
When I use the following query,
SELECT table2.region 'Region',
Count(table1.postcode) AS 'count'
FROM table1
INNER JOIN table2
ON table1.postcode LIKE Concat(table2.postcode, '%')
I get
Region | count
Leeds | 2
where it should be 1 because there is only one record on Table1. Any solution for this ?
Sounds like you need to use DISTINCT
:
SELECT table2.region 'Region',
COUNT( DISTINCT table1.log_id ) as 'count'
FROM table1
INNER JOIN table2 ON
table1.postcode LIKE CONCAT( table2.postcode, '%' )
I replaced postcode with log_id as it perhaps is your unique column.
EDIT: While I'm not exactly sure what you're looking for, here's an alternative approach using a subquery:
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.