如何在一个 MySQL 查询中从两个不同的表中选择记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2529656/
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 can I select records from two different tables in one MySQL query?
提问by Fernando
I have first names stored in one table and last names stored in another. I know this is silly but I am trying out different things as I'm just starting with MySQL. Anyway is it possible to select the first name from one table and the last name from another in one query? And put the result inside a PHP variable?
我将名字存储在一个表中,而姓氏存储在另一个表中。我知道这很愚蠢,但我正在尝试不同的东西,因为我刚开始使用 MySQL。无论如何,是否可以在一个查询中从一个表中选择名字并从另一个表中选择姓氏?并将结果放在 PHP 变量中?
回答by codaddict
You must have something that binds the two tables together, that is a common key
. Something like Id
in the example below:
您必须具有将两个表绑定在一起的东西,即公共key
. 类似于Id
下面的例子:
Table 1
Id Fname
--------
1 Roger
2 Pete
Table 2
Id Lname
--------
1 Federer
2 Sampras
In that case you can get the full name as:
在这种情况下,您可以获得全名:
SELECT Fname, Lname from T1,T2 where T1.Id = T2.Id;
回答by Naveed
回答by ChrisF
select table1.firstname, table2.lastname from table1, table2
where table1.id = table2.id
See herefor more information.
请参阅此处了解更多信息。
The Full Join
If a SELECT statement names multiple tables in the FROM clause with the names separated by commas, MySQL performs a full join.
完整的加入
如果 SELECT 语句在 FROM 子句中命名多个表,名称以逗号分隔,则 MySQL 执行完整连接。