我们有3张桌子
现在我们想要在查询中进行2次检查。
这是我们尝试过的查询,但没有找到正确的查询,意味着它总是拿起1条记录,但没有找到任何其他随机记录。
select membersurlss.Username, COUNT(membersurlss.ID)
from membersurlss
INNER JOIN users ON membersurlss.Username=users.Username
INNER JOIN matrix1 ON matrix1.Username=users.Username
having COUNT(membersurlss.ID)>1
order by rand() limit 0,1
我们想要随机记录。
答案 0 :(得分:0)
您的查询将计算所有用户的ID。要计算每个用户的ID,您需要使用GROUP BY membersurlss.Username
。
select membersurlss.Username, COUNT(membersurlss.ID)
from membersurlss
INNER JOIN users ON membersurlss.Username=users.Username
INNER JOIN matrix1 ON matrix1.Username=users.Username
GROUP BY membersurlss.Username
having COUNT(membersurlss.ID)>1
order by rand() limit 0,1
如果Username
和users
表中的matrix1
是唯一的,那么这应该有用。
如果membersurlss.ID
是唯一的(或主键),您应该使用DISTINCT
来仅计算membersurlss
表中的出现次数:
select membersurlss.Username, COUNT(DISTINCT membersurlss.ID)
from membersurlss
INNER JOIN users ON membersurlss.Username=users.Username
INNER JOIN matrix1 ON matrix1.Username=users.Username
GROUP BY membersurlss.Username
having COUNT(DISTINCT membersurlss.ID)>1
order by rand() limit 0,1