[英]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
. 当前应该做的是,当选择的2行
A_id
不在B
value_1
或value_2
中时,从A
选择2行。 And the rows in B
are specific to individual users with userid
. B
中的行特定于具有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. 我需要做的是也使它也可以检查
B
是否已经有N行与A_id
(在value_1
或value_2
)和userid
相匹配,并且如果有N行以上,则不选择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. 技巧的一部分是将您的条件移到“左联接”的ON子句中。 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.
如果B中没有行与给定用户的value_1或value_2匹配,则根据定义,行数将为零。 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?
您是否想要在这样的情况下,在给定条件下B中只能有最大数量的行匹配? 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.