Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Multiple Columns From Multiple Tables

Tags:

mysql

I'm a beginner at MySQL and I'm having a hard time trying to figure out how to solve this problem:

I have two tables with many entries each. Let's say these are the tables:

   Table 1       ||          Table 2
-------------    ||    -------------------
| dt1 | dt2 |    ||    | dt3 | dt4 | dt5 |
-------------    ||    -------------------
|  1  | abc |    ||    |  3  | wsx | 123 |
|  7  | asd |    ||    |  3  | qax | 456 |
| 19  | zxc |    ||    |  4  | rfv | 789 |
-------------    ||    -------------------

What I want to do is to have as a result one table with columns "dt2", "dt4" and "dt5" and with only one entry. For that, the query I'll apply to each table may even have to LIMIT the results. To get the results I want from each table separetelly I would do the following:

SELECT `dt2` FROM `table1` WHERE `dt1`=7;

and

SELECT `dt4`,`dt5` FROM `table2` WHERE `dt3`=3 LIMIT 0,1;

One more thing, I don't want to use a subquery for each column, because in the real thing I'm trying to solve, I'm calling 5 or 6 columns from each table.

Just to make clear, what I want to get is something like this:

-------------------
| dt2 | dt4 | dt5 |
-------------------
| asd | qax | 456 |
-------------------
like image 807
Henrique Müller Avatar asked Dec 12 '22 07:12

Henrique Müller


1 Answers

SELECT a.dt2, b.dt4, b.dt5
FROM table1 a, table2 b
WHERE a.dt2 = 'asd'
LIMIT 0,1;
like image 182
Ben Avatar answered Dec 31 '22 07:12

Ben