SQL SELECT from multiple tables or JOIN
I have two tables from which I need to get data in the same SELECT
output. The point is, I need to limit the number of results.
Let's say I have a column ID
that is unique in table1
, but in table2
it has many rows with ID
.
Now I just want to indicate how many different ones ID
I have in table1
and some other information stored in table2
.
How can I get the desired result, which I show at the end?
To make it clear that I have used the messenger database for the example.
Table
T1
Id_thread Date
1 13Dic
2 12Dic
T2
Id_thread Message Name
1 Hi Someone
1 Hi to you Someone
2 Help me? Someother
2 Yes! Someother
Desired output
T1.Id_thread T2.Name T1.Date
1 Someone 13Dic
2 Someother 12Dic
source to share
Use JOIN
and GROUP BY
:
SELECT t1.Id_thread, t2.Name, t1.Date
FROM t1
JOIN t2 ON t1.Id_thread = t2.Id_thread
GROUP BY t1.Id_thread
Note that if it is the Name
same for all rows in t2
that have the same Id_thread
, that column should probably be in t1
. If you fix this, you won't need it JOIN
.
source to share
You have not specified how you want to constrain the results from Table 2. Given that you just want one row, you can use CROSS APPLY:
Select T1.Id_thread,T2Table.Name,T1.Date From T1
Cross Apply (Select Top 1 T2.Name From T2 Where T2.Id_thread=T1.Id_thread) T2Table
You can specify other conditions in the inner Select statement if you like.
source to share