Jump to content

Too many sub queries


Suchy

Recommended Posts

I have 2 tables, friends:

user | friend

-----------------

  1        2

  4        1

  4        2

  4        3

 

and posts:

post  |  user  |  time

-------------------------

aa        1          10:00

bb        2          10:01

cc          1          11:00

dd        3          12:00

 

anyway Im trying to get all the posts that a certain user and all of his friends have made. My query is:

SELECT post, user , time 
FROM posts 
WHERE user = (
                  SELECT friend FROM friends WHERE user = 1
                  UNION SELECT user FROM friends WHERE friend = 1
              )

 

But its not working, im getting: "Too many sub queries" error

 

Link to comment
Share on other sites

SELECT post, user , time 
FROM posts 
WHERE user = (
                  SELECT friend FROM friends WHERE user = 1
                  UNION SELECT user FROM friends WHERE friend = 1
              )

 

The problem with that query, is that you are comparing a scalar value (the 'user' attribute) with a set (the subquery).

 

Unfortunately, in SQL, instead of notifying you of the true problem with some unambiguous description,

you are instead notified with a cryptic message (i.e., "too many subqueries").

 

-----

 

To fix that, you only need to change your method of comparison, like so:

SELECT post, user , time 
FROM posts 
WHERE user IN (
SELECT friend FROM friends WHERE user = 1
UNION 
SELECT user FROM friends WHERE friend = 1
)

IOW, change the '=' operator to the 'IN' operator, which is a set operator.

 

Hope it helps.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.