0

I'm a little lost as how to run two mysql queries as one(return one result set to be sorted etc).

I understand how to do multiple JOINS but need to combine the below which is more than just a multiple join - it would include a multiple where etc.

1st query

     sql = "SELECT s.id, s.song_name
           FROM `songs` as s
           INNER JOIN `artists` as a ON s.artist_id = a.id
           WHERE ((`a`.id = #{search}))"

2nd query

   sql = "SELECT s.id, s.song_name
      FROM `songs` as s
      INNER JOIN `similarments` as si ON s.artist_id = si.artist_id
      WHERE ((`si`.similar_id = #{search}))"

And then run both queries at once so I can ORDER them etc. Or combine them as one big query (maybe put an OR somewhere)?

Thanks!

1
  • LEFT JOIN to both tables in a single query from SONGs... Commented May 11, 2010 at 22:23

1 Answer 1

4

The simple way to run two queries and combine the results is to use UNION (or UNION ALL if you don't wish to remove duplicates). In your case it would look like this:

(
    SELECT s.id, s.song_name
    FROM `songs` as s
    INNER JOIN `artists` as a ON s.artist_id = a.id
    WHERE ((`a`.id = #{search}))
)
UNION
(
    SELECT s.id, s.song_name
    FROM `songs` as s
    INNER JOIN `similarments` as si ON s.artist_id = si.artist_id
    WHERE ((`si`.similar_id = #{search}))
)
ORDER BY ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.