问题
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