开发者

How to join only one column?

开发者 https://www.devze.com 2023-03-31 01:30 出处:网络
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id WHERE table1.id = 1 I开发者_如何学Python need to join only one column from table 2, say first_name.
SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1

I开发者_如何学Python need to join only one column from table 2, say first_name. How can I do that?


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


Take your original code and substitute * with table1.*, table2.YourChosenColumn

 SELECT table1.*, table2.YourChosenColumn
 FROM table1 LEFT JOIN table2 
 ON table1.id = table2.table1_id 
 WHERE table1.id = 1  


Do you mean in addition to your already stated query:

SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1 and table1.first_name = table2.first_name
0

精彩评论

暂无评论...
验证码 换一张
取 消