MySQL 如何只加入一列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7219385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to join only one column?
提问by Kevin Grace
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?
我只需要加入表 2 中的一列,比如 first_name。我怎样才能做到这一点?
回答by NullUserException
Assuming that you mean "select one column from table 2":
假设您的意思是“从表 2 中选择一列”:
SELECT table1.*, table2.first_name
FROM table1
LEFT JOIN table2
...
回答by MTK
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:
假设 table1 在 database1 中,table2 在 database2 中。最初我试过这个:
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).
奇怪的是,如果我从 PHP PDO 尝试这个查询,没有错误,但结果包含来自 database2.table2 的所有列(预计只有 first_name 列)。
But if I have tried the same query from phpmyadmin got a sintax error:
但是,如果我从 phpmyadmin 尝试了相同的查询,则会出现 sintax 错误:
Table 'database2.table1' doesn't exist
表“database2.table1”不存在
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
回答by davecoulter
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
回答by Jacob Hamfeldt Kold
Take your original code and substitute * with table1.*, table2.YourChosenColumn
获取您的原始代码并将 * 替换为 table1.*, table2.YourChosenColumn
SELECT table1.*, table2.YourChosenColumn
FROM table1 LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1