简体   繁体   中英

Select 2 Rows from Table when COUNT of another table

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM