[英]mysql inner join count issue
我有兩個表: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,因為表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
確定8小時后的解決辦法。 在最終用戶輸入郵政編碼之前,將郵政編碼修剪掉任何空格,然后將str_replace替換為空,然后刪除字符串的最后3個字母/數字。 並將其與原始郵政編碼一起另存為一列,現在您將擁有類似於LS1的郵政編碼存儲。 LS11,而不是使用like的內部聯接,請使用=。 這是我認為唯一的出路。
請參閱此鏈接以獲取更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.