【发布时间】:2018-04-04 20:44:32
【问题描述】:
我正在尝试在 wordpress 中构建用户通知系统。我有一个查询,它连接 wp_posts 表中的行,这些行的 post_status 为发布,post_author 为 1,post_type 为 user_notification。有两行满足这些要求。 total_unread 列始终为 4,整个查询仅返回 1 行。我究竟做错了什么?这是SqlFiddle
这是表结构
CREATE TABLE `wp_posts` (
`ID` bigint(20),
`post_author` bigint(20) DEFAULT '0',
`post_content` longtext NULL,
`post_status` varchar(20) DEFAULT 'publish',
`post_type` varchar(20) DEFAULT 'post'
) ENGINE=InnoDB;
INSERT INTO wp_posts
(ID, post_author, post_content, post_status, post_type)
VALUES(1, 1, 'John Smith would like to be friends!', 'publish', 'user_notification');
INSERT INTO wp_posts
(ID, post_author, post_content, post_status, post_type)
VALUES(2, 1, 'Sally Miller shared your post!', 'publish', 'user_notification');
这里是查询:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID, wp_posts.post_status, COUNT(unread.post_status) as total_unread
FROM wp_posts
JOIN wp_posts AS unread ON unread.post_author = 1 AND unread.post_status = 'publish' AND unread.post_type = 'user_notification'
WHERE wp_posts.post_author IN (1)
AND wp_posts.post_type = 'user_notification'
ORDER BY wp_posts.ID DESC LIMIT 0, 5
【问题讨论】:
-
Offtopic:您可以从 WHERE 子句中删除
1=1,它总是正确的,而且看起来很笨拙 -
啊,是的,我不确定 Wordpress 为什么将它添加到他们的 WP_Query 函数中。
-
您期待什么结果?因为您使用的是没有 GROUP BY 的 COUNT,所以总是产生一条记录。而且您显然想要更多记录,因为您使用的是
LIMIT 0, 5..此外,我真的不知道为什么您在该表上使用了自联接..
标签: mysql