Thursday 8 November 2018

Mysql: How to join only one column?


SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1
I need to join only one column from table 2, say first_name. How can I do that?

 Answers


Assuming that you mean "select one column from table 2":
   SELECT table1.*, table2.first_name
     FROM table1
LEFT JOIN table2
...



The accepted answer is the correct answer but I have encountered a strange error when the tables are in two different databases:
Assuming that table1 is in database1 and table2 is in database2. Initially I have tried this:
SELECT *, database2.table2.first_name FROM table1
LEFT JOIN database2.table2
ON database1.table1.id = database2.table2.table1_id
WHERE table1.id = 1
The strange thing is that if I try this query from PHP PDO there were no errors but the result contained all columns from database2.table2 (expected only first_name column).
But if I have tried the same query from phpmyadmin got a sintax error:
Table 'database2.table1' doesn't exist
So, for solve that, then all databases need to be specified implicitly like this:
SELECT database1.table1.*, database2.table2.first_name FROM database1.table1
LEFT JOIN database2.table2
ON database1.table1.id = database2.table2.table1_id
WHERE database1.table1.id = 1

0 comments:

Post a Comment