我试图通过使用SQL查询来获得许多具有角色的用户 - 订阅者,两个帖子类型的数量以及来自帖子的元值:
SELECT
SUM(CASE WHEN meta_key='wp_capabilities' AND meta_value LIKE '%subscriber%' THEN 1 ELSE 0 END) AS users,
SUM(CASE WHEN post_type='post' AND post_status='publish' THEN 1 ELSE 0 END) AS posts,
SUM(CASE WHEN post_type='updates' AND post_status='publish' THEN 1 ELSE 0 END) AS updates, meta_value AS version
FROM wp_usermeta,wp_posts,wp_postmeta WHERE meta_key='content_version' AND post_id=1
没有结果并显示错误"#1052 - 列' meta_key'在字段列表中是不明确的"
任何人都可以帮助我做错了吗?
我想得到的结果视图应该是:
| users | posts | updates | version |
-------------------------------------------
| 2 | 5 | 2 | 1 |
谢谢
更新
当我使用表别名更新查询时:
SELECT
SUM(CASE WHEN a.meta_key='wp_capabilities' AND a.meta_value LIKE '%subscriber%' THEN 1 ELSE 0 END) AS users,
SUM(CASE WHEN b.post_type='post' AND b.post_status='publish' THEN 1 ELSE 0 END) AS posts,
SUM(CASE WHEN b.post_type='updates' AND b.post_status='publish' THEN 1 ELSE 0 END) AS updates, c.meta_value AS version
FROM wp_usermeta AS a, wp_posts AS b, wp_postmeta AS c WHERE c.meta_key='content_version' AND post_id=1
它带来了错误的结果,似乎SUM正在计算表中的每条记录。以前有人有这个问题吗?我使用的是5.5.44-MariaDB
答案 0 :(得分:1)
出现1052错误,只是说在搜索表后,它不知道列应该来自哪个表,因为列名出现在多个表中。
在您的情况下,您有3个表。您需要使用您头脑中的表来限定meta_key列,而不是在我的数据库引擎头中(因为它在那里不明确)。
如果这意味着在列名称的前面做tablename.
(点)或别名,那么这就是要走的路。顺便说一下,这始终是要走的路。
在纠正一列之后,您可能会遇到下一个错误。继续相应。
编辑: 你想看一个例子,见下文。
create table car
( -- a particular car on the lot, not a make and model in general
id int auto_increment primary key,
carId int not null, -- this is a lookup in some other table to identify year/make/model (non unique)
paintId int not null, -- as this is a particular car, it has a particular color !
category varchar(20), -- lease, for-sale, demo, dumpItFast, etc
price int not null
-- Foreign Key constraints not shown such as carId and paintId
-- other indexes not shown
);
create table paint
( id int auto_increment primary key,
name varchar(20) not null,
category varchar(50) -- metallic, undercarriage, matte, clear coat
);
select id,category,price,name
from car
join paint
on paint.id=car.paintId
错误代码:1052。列' id'在字段列表中是不明确的
select car.id,category,price,name
from car
join paint
on paint.id=car.paintId
错误代码:1052。列'类别'在字段列表中是不明确的
select car.id,car.category,price,name
from car
join paint
on paint.id=car.paintId
- 那会成功
坦率地说,最好在所有列上使用别名,这是毫无疑问的。否则下一个看着它的人,即使是你,总是在猜测。