Hello guys, Is it possible to select only some columns from a table on a LEFT JOIN?
+8
A:
Of course. Just list the columns you want to select as you would in any query:
SELECT table1.column1, table1.column2, table2.column3
FROM table1
LEFT JOIN table2 ON (...)
Note that I've included the table1.
or table2.
prefix on all columns to be sure there aren't any ambiguities where fields with the same name exist in both tables.
VoteyDisciple
2009-08-25 17:17:25
Probably worth adding that it's a good idea to prefix them with the table they're from e.g. table1.column1, table2.column2 etc so stop ambiguity errors and just for general readability.
Gavin Gilmour
2009-08-25 17:18:39
Also, if you have any ambiguous column names, you can specify which table to use with dot syntax: SELECT table1.id, table2.name FROM table1 LEFT JOIN table2 ON (...)
sixthgear
2009-08-25 17:19:55
Good point. Edited accordingly.
VoteyDisciple
2009-08-25 17:20:02
I want to select the columns from the table I'm about to join, not from the first table.
Psyche
2009-08-25 17:20:22
@Psyche: It's no different. As Vorey depicts, table2.column3 is coming from the joined table, not the original source table.
Adam Robinson
2009-08-25 17:21:43