Suchy Posted July 4, 2011 Share Posted July 4, 2011 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 https://forums.phpfreaks.com/topic/241085-too-many-sub-queries/ Share on other sites More sharing options...
ebmigue Posted July 6, 2011 Share Posted July 6, 2011 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 https://forums.phpfreaks.com/topic/241085-too-many-sub-queries/#findComment-1238814 Share on other sites More sharing options...
fenway Posted July 6, 2011 Share Posted July 6, 2011 Though is could be re-written as a join, too, since large IN() clauses aren't optimal. Link to comment https://forums.phpfreaks.com/topic/241085-too-many-sub-queries/#findComment-1238975 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.