0

I'm using MySQL

I have three tables:

accounts {
    account_id,
    username
}

account_ips {
    idaccount_ips,
    account_id,
    ip
}

account_bans {
    ban_id
    account_id,
    expires
}

Need to get grouped count of accounts per ip that are not in bans table. (See query below)

I've tried the following, but it is way too slow (44s):

SELECT DISTINCT a.account_id, count(DISTINCT a.account_id)
  FROM account_ips AS a
 WHERE NOT EXISTS(
    SELECT 1
      FROM account_bans AS b
     WHERE b.expires > 1340341272 AND b.account_id = a.account_id)
 GROUP BY a.ip
HAVING count(DISTINCT a.account_id) > 3
 ORDER BY count(DISTINCT a.account_id) DESC;

Explain output the following:

1, 'PRIMARY', 'a', 'ALL', '', '', '', '', 304745, 'Using where; Using temporary; Using filesort'
2, 'DEPENDENT SUBQUERY', 'b', 'ALL', '', '', '', '', 1851, 'Using where'
4

2 に答える 2

2

このようにする必要があります-

SELECT AIP.IP, COUNT(AIP.ACCOUNT_ID)
FROM ACCOUNT_IPS AIP
LEFT JOIN ACCOUNTS A ON AIP.ACCOUNT_ID=A.ACCOUNT_ID
LEFT JOIN ACCOUNT_BANS AB ON A.ACCOUNT_ID=AB.ACCOUNT_ID
WHERE
AB.BAN_ID IS NULL
GROUP BY AIP.IP

b.expires > 1340341272 も考慮する必要がある場合、クエリは次のようになります -

SELECT AIP.IP, COUNT(AIP.ACCOUNT_ID)
FROM ACCOUNT_IPS AIP
LEFT JOIN ACCOUNTS A ON AIP.ACCOUNT_ID=A.ACCOUNT_ID
LEFT JOIN ACCOUNT_BANS AB ON A.ACCOUNT_ID=AB.ACCOUNT_ID
WHERE
AB.BAN_ID IS NULL
OR AB.EXPIRES <= 1340341272
GROUP BY AIP.IP
于 2012-06-22T05:05:56.907 に答える
0

とは対照的に、 を試してleft join、右側の表の ips の null を取得しWHERE NOT EXISTSます。

FROM account_ips a
LEFT JOIN account_bans b ON b.account_id = a.account_id
WHERE b.account_id IS NULL 
于 2012-06-22T05:06:46.480 に答える