join 2 tables case sensitive upper and lower case

放肆的年华 提交于 2019-12-11 03:48:50

问题


I have 2 tables and need to get result on brand code.

In the database i have for example 2 different brands but their code is the same (only difference in lower and upper case). For example:

code Name ab Nike AB Adidas

How to inner join 2 tables on code to get this 2 separately?

Right now after inner join i get total sum of this 2.

SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
FROM A
INNER JOIN B
ON A.Code=B.Code
GROUP BY Code, BrandName

This query will give me wrong result as it does not join sensitively on upper and lower case.

Please help :)


回答1:


There are at least two quick ways you can solve this.

1. You specify a case-sensitive collation (rules for comparing strings across characters in a character set) for A.Code and B.Code. In MySQL and a few other database management systems, the default collation is case-insensitive.

That is, assuming that you're using MySQL or similar, you'll have to modify your statement as such:

SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
FROM A
INNER JOIN B
ON A.Code=B.Code COLLATE latin1_bin
GROUP BY Code, BrandName

If, however, you plan on only performing case-sensitive queries on A and B, it may be in your interest to set the default collation on those two tables to case-sensitive.

Please see How can I make SQL case sensitive string comparison on MySQL?

2. Cast A.Code and B.Code to a binary string and compare the two. This is an simple way to compare two strings, byte-by-byte, thus achieving case-insensitivity.

SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
FROM A
INNER JOIN B
ON BINARY A.Code=B.Code
GROUP BY Code, BrandName



回答2:


Since you use a collation that is case insensitive and want to differentiate on case try using the collate keyword with a suitable case-sensitive collation:

INNER JOIN B
ON A.Code COLLATE Latin1_General_CS_AS_KS_WS  = B.Code COLLATE Latin1_General_CS_AS_KS_WS 


来源:https://stackoverflow.com/questions/29533346/join-2-tables-case-sensitive-upper-and-lower-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!