tags:

views:

318

answers:

2

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
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
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
Good point. Edited accordingly.
VoteyDisciple
I want to select the columns from the table I'm about to join, not from the first table.
Psyche
@Psyche: It's no different. As Vorey depicts, table2.column3 is coming from the joined table, not the original source table.
Adam Robinson
A: 

If you want some of table1's columns and some of table2's columns, you would do something like

SELECT t1.col1, t1.col2, t1.col3, t2.col1, t2.col2, t2.col3
FROM table1 t1
LEFT JOIN table2 t2
ON...
flayto
Great! Thank you guys!
Psyche