views:

87

answers:

1

Here is the code that I currently have:

   SELECT `A`.* 
     FROM `A`
LEFT JOIN `B` ON `A`.`A_id` = `B`.`value_1` 
    WHERE `B`.`value_2` IS NULL 
      AND `B`.`userid` IS NULL
 ORDER BY RAND() LIMIT 2

What it currently is supposed to do is select 2 rows from A when the 2 rows A_id being selected are not in value_1 or value_2 in B. And the rows in B are specific to individual users with userid.

What I need to do is make it also so that also checks if there are already N rows in B matching a A_id (either in value_1, or value_2) and userid, and if there are more than N rows, it doesn't select the A row.

+1  A: 

The following would handle your first request:

Select ...
From A
    Left Join B
        On ( B.value_1 = A.A_id Or B.value_2 = A.A_id )
            And B.userid = @userid
Where B.<non-nullable column> Is Null

Part of the trick is moving your criteria into the ON clause of the Left Join. I'm not sure how the second part of your request fits with the first part. If there are no rows in B that match on value_1 or value_2 for the given user, then by definition that row count will be zero. Is it that you want it be the situation where there can only be a maximum number of rows in B matching on the given criteria? If so, then I'd write my query like so:

Select ...
From A
Where   (
        Select Count(*)
        From B B2
        Where ( B2.value_1 = A.A_id Or B2.value_2 = A.A_id )
            And B2.userid = @userid
        ) <= @MaxItems
Thomas
Thanks Thomas!It's working, for the most part. Except I am getting at times the same row return twice (it should never have the same row return twice), and sometimes it is returning rows that the "`B2.value_1 = A.A_id Or B2.value_2 = A.A_id`" should be preventing it from doing so. Usually it seems like they are in the different order when they are.
Marcus
@Marcus - From which query? The first query should never return more than one PK value for A. If you think it is returning the same row (same row of what?) multiple times, can you show us some sample input and the output it is producing?
Thomas
Oh, I see what I did... I misunderstood you and combined both your queries... Whoops. I've got it work now. Thanks again!
Marcus