Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join only one column?

Tags:

join

mysql

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?

like image 770
Kevin Grace Avatar asked Aug 28 '11 06:08

Kevin Grace


People also ask

How do I only join one column in SQL?

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

How do I combine one column from another table?

SELECT * FROM table1 JOIN table2 ON table1. column_name = table2. column_name; The INNER JOIN in SQL joins two tables according to the matching of a certain criteria using a comparison operator.

How do you join columns in a table?

To merge table columns in HTML use the colspan attribute in <td> tag. With this, merge cells with each other. For example, if your table is having 4 rows and 4 columns, then with colspan attribute, you can easily merge 2 or even 3 of the table cells.

Can you join columns with different names?

The corresponding columns can have different names, as they do in our example. By default, the name of the corresponding column in the output will be taken from the first SELECT statement. If necessary, you can set the names for the resulting columns using the AS keyword.


2 Answers

Assuming that you mean "select one column from table 2":

   SELECT table1.*, table2.first_name      FROM table1 LEFT JOIN table2 ... 
like image 63
NullUserException Avatar answered Sep 19 '22 11:09

NullUserException


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 
like image 28
MTK Avatar answered Sep 18 '22 11:09

MTK