-3

我在此查询中遇到错误。我不知道它有什么问题。帮助将不胜感激。

SELECT Email, UserID, FirstName, LastName,
count(*) as userTextCount FROM user LEFT JOIN posts ON posts.PostedAsId = user.UserID and
PostedAs = 'USER' and PostType = 'text',
count(*) as userMediaCount FROM user LEFT JOIN posts ON posts.PostedAsId = user.UserID and
PostedAs = 'USER' and PostType = 'media'
WHERE 1
GROUP BY Email, UserID, FirstName, LastName

错误:

#1064 - You have an error in your SQL syntax; 
MySQL server version for the right syntax to use near 'count(*) as userMediaCount FROM
user LEFT JOIN posts ON posts.PostedAsId = user.' at line 3

用户表包含:Email、UserId、FirstName、LastName 和帖子表包含所有帖子,我需要按特定用户计算帖子。

谢谢。

4

3 回答 3

4

您可以尝试使用看起来像这样的条件计数

SELECT Email, UserID, FirstName, LastName,
       SUM(CASE WHEN PostedAs = 'USER' and PostType = 'text' THEN 1 ELSE 0) userTextCount,
       SUM(CASE WHEN PostedAs = 'USER' and PostType = 'media' THEN 1 ELSE 0) userMediaCount,
  FROM user u LEFT JOIN posts p
    ON p.PostedAsId = u.UserID 
 GROUP BY Email, UserID, FirstName, LastName

或者

SELECT Email, UserID, FirstName, LastName,
       SUM(CASE WHEN PostType = 'text'  THEN 1 ELSE 0) userTextCount,
       SUM(CASE WHEN PostType = 'media' THEN 1 ELSE 0) userMediaCount,
  FROM user u LEFT JOIN posts p
    ON p.PostedAsId = u.UserID 
   AND p.PostedAs = 'USER'
 GROUP BY Email, UserID, FirstName, LastName
于 2013-11-01T15:22:24.143 回答
0
SELECT
    Email,
    UserID,
    FirstName,
    LastName,
    PostedAs,
    PostType
FROM
    user
    LEFT JOIN posts ON posts.PostedAsId = user.UserID
WHERE
    PostedAs = 'USER'
    AND PostType IN ('text', 'media')

你应该告诉我们你到底需要什么。也许这个查询将是开始。

于 2013-11-01T15:25:31.900 回答
0

你可以试试这个,它会给你一行 postType 媒体和另一行 post type text,你可以在你的业务层处理它们

SELECT Email, UserID, FirstName, LastName, PostType, count(PostType)
FROM user LEFT JOIN posts ON posts.PostedAsId = user.UserID 
WHERE PostedAs = 'USER' and PostType = 'media' OR  PostType = 'text'
GROUP BY Email, UserID, FirstName, LastName
于 2013-11-01T15:24:04.920 回答