8

I don't get it. I've tried:

SELECT
table1.name, CONCAT( country,  '.', id ) AS table1.code,
table2.name
FROM tabel1
LEFT OUTER JOIN
table2 ON ( table1.code = table2.code )

I need to combine country and id to country.id because table2.code has this schema.

Thanks in advance.

2
  • What's the problem? Are you getting null? Commented Mar 9, 2013 at 17:28
  • Did you notice that you typed FROM tabel1 rather than table2? Commented Mar 9, 2013 at 17:29

2 Answers 2

13

If I understand you correct you might need something like this

SELECT t1.name t1_name,
       t2.name t2_name
FROM table1 t1 LEFT JOIN
     table2 t2 ON CONCAT(t1.country,  '.', t1.id ) = t2.code

SQLFiddle example

Sign up to request clarification or add additional context in comments.

4 Comments

Your Fiddle link goes to a blank fiddle.
@Sparky This fiddle was created more 1.5 years ago. It looks like SQLFiddle dropped old fiddles.
I realize that. I just thought you'd like to know so you can update your answer to either remove or fix the fiddle.
This same method also works in Symfony using Doctrine.
7

For anyone pulling his hair out because of the poor performance of ON CONCAT() joins: make sure you cast your non string values to CHAR it improves the performance astronomically:

SELECT t1.name t1_name,
       t2.name t2_name
FROM table1 t1 LEFT JOIN
     table2 t2 ON CONCAT(t1.country,  '.', CAST(t1.id AS CHAR) ) = t2.code

Explanation hides in MySQL docs for CONCAT() function:

…If all arguments are non-binary strings, the result is a non-binary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent binary string form; if you want to avoid that, you can use an explicit type cast

Credit for this goes to Aurimas Mikalauskas.

1 Comment

In case someone wants to set COLLATE: SELECT CAST('test' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.