1

我正在尝试对我的用户数据库运行查询,但遇到了一些麻烦。我想获取相关行的数量并以此为基础。我会让我的场景解释:

用户可以在我的应用中拥有_many 个视频。就我而言,我想返回所有没有视频的用户。还有其他一些条件,但这是我遇到麻烦的条件。理想情况下,我的查询类似于(有点 sudo 代码):

SELECT count(*) FROM users 
JOIN videos ON users.id=videos.user_id
WHERE
  users.some_attribute = 1
  OR
  (users.last_login >= '03/18/2012' AND COUNT(videos) > 0)

任何和所有的帮助表示赞赏。

谢谢!!- 杰夫

4

4 回答 4

0

您可以使用具有 HAVING 属性的 GROUP BY

SELECT usercolumns, count(videos.user_id) 
FROM users 
    LEFT OUTER JOIN videos ON users.id=videos.user_id
WHERE users.some_attribute = 1
GROUP BY usercolumns HAVING users.last_login >= '03/18/2012' AND COUNT(videos.user_id) > 0

如果你真的想要所有的列,你也可以使用 subQuery

SELECT *
FROM (
    SELECT userscolumns, count(videos.user_id) 
    FROM users 
        LEFT OUTER JOIN videos ON users.id=videos.user_id
    WHERE users.some_attribute = 1
    GROUP BY userscolumns
) A
WHERE users.last_login >= '03/18/2012' 
AND COUNT(videos.user_id) > 0
于 2013-03-18T17:45:11.647 回答
0

您可以在 SQL 中使用 Have 语句:

SELECT count(*) FROM users 
JOIN videos ON users.id=videos.user_id
WHERE  users.some_attribute = 1   OR   users.last_login >= '03/18/2012'
HAVING COUNT(videos.<some_column>) > 0)

添加编辑以响应以下评论:

SELECT count(*) FROM users 
WHERE  users.some_attribute = 1   
UNION 
SELECT count(*) FROM users 
JOIN videos ON users.id=videos.user_id
WHERE  users.last_login >= '03/18/2012'
HAVING COUNT(videos.<some_column>) > 0)
于 2013-03-18T17:46:14.040 回答
0

我认为不存在最好

SELECT count(*) 
FROM users 
WHERE
users.some_attribute = 1
OR
(users.last_login >= '03/18/2012' 
and not exists 
 (
 select count(videos.videofield) 
 from videos 
 where users.id=videos.user_id
 )
)
于 2013-03-18T17:50:08.050 回答
0
SELECT u.user FROM users u
LEFT JOIN videos v ON u.id=v_id
WHERE v_id IS NULL AND 
  (users.some_attribute = 1
  OR
  users.last_login >= STR_TO_DATE('03/18/2012', '%m/%d/%Y'))
于 2013-03-18T17:52:25.340 回答