Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Select and count from different table?

Tags:

sql

tsql

asp.net

I have a table (Threads) containing a field (id). I would like to select every row from Threads, as well as the number of rows in the table Posts where the field Posts.thread is the same as Threads.id.

How can this be done in SQL?

(Something like this pseudo-SQL: SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads)

like image 794
Ry- Avatar asked Jul 12 '11 16:07

Ry-


People also ask

Can you SELECT from two different tables 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.

How do I count records of all tables in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I count records from two tables in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.


2 Answers

Sure - something like this?

SELECT 
    t.ThreadID,
    (SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
    dbo.Threads t
like image 89
marc_s Avatar answered Sep 20 '22 14:09

marc_s


SELECT t.id, COUNT(p.thread)
FROM Threads AS t
    LEFT OUTER JOIN Posts AS p
        ON t.id = p.thread
GROUP BY t.id
like image 23
Waqas Raja Avatar answered Sep 18 '22 14:09

Waqas Raja