Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine two queries in SQL? (subquery)

Issue

I am having trouble combining two SQL queries into one. I want to use part of the data from the first query to reach into a different table and retrieve some more information.

Description

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have the following query that gets the top 50 Stackoverflow posts that contain the word "html" in the title:

SELECT  top 50
        Id AS [Post Link],
        Title,
        Score,
        OwnerUserId
FROM    Posts
WHERE  Title LIKE lower('%html%')
ORDER BY
        Score DESC

When I have retrieved this data, I’d like to take the 50 OwnerUserIds and query the Users table for their AboutMe and display it with the result from the "main query". As I understand it, this can be achieved using a subquery, but I’m not quite sure how. What I want to do is:

SELECT AboutMe 
FROM Users 
WHERE Id = OwnerUserId (having taken the OwnerUserId from the first query)

Any help is greatly appreciated

>Solution :

I don’t think you want a subquery which would probably look something like

SELECT AboutMe 
FROM Users 
WHERE Id in
(
   SELECT  top 50 
   OwnerUserId
   FROM    Posts
   WHERE  Title LIKE lower('%html%')
   ORDER BY
        Score DESC
)

I think you really want one query to return all the results by joining the two tables, e.g. something like

SELECT  top 50
        Posts.Id AS [Post Link],
        Posts.Title,
        Posts.Score,
        Posts.OwnerUserId,
        Users.AboutMe
FROM    Posts
Inner join users on users.id = Posts.OwnerUserId
WHERE  Title LIKE lower('%html%')
ORDER BY
        Posts.Score DESC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading