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
)
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.
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).
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.
Sure - something like this?
SELECT
t.ThreadID,
(SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
dbo.Threads t
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With