我在此查询中收到错误。 我不知道它有什么问题。 将不胜感激。
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
ERROR:
#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和posts表包含所有帖子,我需要按特定用户计算帖子。
感谢。
答案 0 :(得分: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
答案 1 :(得分:0)
你可以试试这个,它会给你一行postType媒体和另一个带有帖子类型的文本,你可以在你的业务层处理它们
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
答案 2 :(得分: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')
你应该告诉我们你需要什么。也许这个查询将是开始。