如何在一个MySQL查询中从两个不同的表中选择记录?

时间:2022-09-10 11:59:27

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变量中?

3 个解决方案

#1


6  

You must have something that binds the two tables together, that is a common key. Something like Id in the example below:

您必须有一些东西将两个表绑定在一起,这是一个公共键。如下例中的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;

#2


0  

select table1.firstname, table2.lastname from table1, table2
    where table1.id = table2.id

See here for 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将执行一个完整的连接。

#3


0  

Use joins

使用连接

SELECT firstName, lastName  
FROM Table1, Table2 
WHERE (Table1.id = Table2.id)

#1


6  

You must have something that binds the two tables together, that is a common key. Something like Id in the example below:

您必须有一些东西将两个表绑定在一起,这是一个公共键。如下例中的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;

#2


0  

select table1.firstname, table2.lastname from table1, table2
    where table1.id = table2.id

See here for 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将执行一个完整的连接。

#3


0  

Use joins

使用连接

SELECT firstName, lastName  
FROM Table1, Table2 
WHERE (Table1.id = Table2.id)