简体   繁体   English

仅获得具有特定联接表计数的用户

[英]Only get users with a specific joined table count

My SqlFiddle 我的SqlFiddle

Seems pretty simple but for the life of me I cannot seem to get the results I want. 看起来很简单,但是对于我的一生,我似乎无法获得想要的结果。 Keep in mind this is happening on a server that has over 6 million records so it has to be efficient. 请记住,这是在具有600万条记录的服务器上发生的,因此必须高效。

I want to get the users who are joined to item table that have status 1 of 3 count or higher only not the users who have status of 1 on an item 2 times has to be >= 3. 我想让加入状态为1等于3或更高的项目表的用户加入,而并非项目2上具有状态1的用户必须> = 3。

SELECT 
    user.id,
    user.name,
    item.id as item_id,
    itemstatus.item_status,
    COUNT(item.status) as status
FROM user
JOIN item ON (user.id = item.user_id)
JOIN itemstatus ON (item.status = itemstatus.id)
WHERE item.status = 1
GROUP BY user.id

My current query above get all with a count. 我上面的当前查询非常有用。 How do I get only the ones that have the 3 or above count. 我如何只获得3以上的计数。 Thanks in advance. 提前致谢。 I hope I made this clear. 我希望我说清楚了。

If I understand you correctly, you only want records with COUNT(item.status) greater than or equal to 3, in which case you need to use the HAVING clause after your GROUP BY clause. 如果我理解正确,则只希望COUNT(item.status)大于或等于3的记录,在这种情况下,您需要在GROUP BY子句之后使用HAVING子句。 The HAVING clause is sort of like a WHERE clause for aggregate values. HAVING子句有点像用于聚合值的WHERE子句。

SELECT 
    user.id,
    user.name,
    item.id as item_id,
    itemstatus.item_status,
    COUNT(item.status) as status
FROM user
JOIN item ON (user.id = item.user_id)
JOIN itemstatus ON (item.status = itemstatus.id)
WHERE item.status = 1
GROUP BY user.id
HAVING COUNT(item.status) >= 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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