MySQL - how to find similar data in two mysql tables?

我们两清 提交于 2020-12-15 04:54:28

问题


I have two table like this :

table1

| cat   | id   | 
|-----  |------|
| 110** |  12  | 
| 110** |  18  |  
| 110** |  13  |
----------------

table2

| cat   | qty  | 
|-----  |------|
| 11012 |  2   | 
| 11017 |  8   |  
| 11016 |  1   |
----------------

result

| cat   | 
|-----  |
| 11012 | 
---------

can I combine cat,id columns in table1 (like 11012) to get the same value in cat column in table2 (like 11012)? I tried a query like this:

SELECT a.cat,a.id FROM table1 a JOIN table2 b ON a.cat LIKE CONCAT('%', b.cat, '%') 

but I didn't get the results I expected.


回答1:


SELECT *
FROM table1 t1
JOIN table2 t2 ON CONCAT(TRIM(TRAILING '*' FROM t1.cat), id) = t2.cat

Logic: remove trailing asterisks from cat, concatenate id, then compare.

fiddle




回答2:


If I understand question correctly, you should do

SELECT a.cat,a.id FROM table1 a JOIN table2 b ON LEFT(a.cat,3) = LEFT(b.cat, 3)


来源:https://stackoverflow.com/questions/64962946/mysql-how-to-find-similar-data-in-two-mysql-tables

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