Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select records from two different tables in one MySQL query?

Tags:

sql

mysql

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?

like image 338
Fernando Avatar asked Mar 27 '10 14:03

Fernando


People also ask

How can I get data from two tables in a single query?

From multiple tables To retrieve information from more than one table, you need to join those tables together. This can be done using JOIN methods, or you can use a second SELECT statement inside your main SELECT query—a subquery.

How do I SELECT two values from two tables in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

Can we SELECT data from two tables in SQL?

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.


1 Answers

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

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;
like image 179
codaddict Avatar answered Oct 17 '22 16:10

codaddict