我的mysql表名为products,其结构/内容如下:
id (int), public_id (int), deleted (bool), online (bool)
1 1 0 1
2 1 0 0
3 1 1 0
4 2 0 1
5 2 0 1
我的问题是,如何选择所有当前在线但未删除的产品。在此示例中仅记录5(public_id 2)。相同的public_id表示相同的产品(分组)id越高,信息越新(排序)。并且产品需要不删除(在哪里)。还有一些其他的陈述,在这种情况下是在线领域。
我需要所有方面(分组,排序和位置),但我无法弄清楚如何。
有什么建议吗?
来自Galz的解释查询结果:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY nomis_houses ref online online 1 const 8086 Using where
2 DEPENDENT SUBQUERY nomis_houses index NULL house_id 4 NULL 9570 Using filesort
PS。这个查询做了诀窍,但非常非常非常缓慢:
select * from
(select * from
(select * from products order by id desc) tmp_products_1
group by public_id) tmp_products_2
where deleted = '0' AND online = '1'
答案 0 :(得分:2)
基于萨钦的回答和你的评论,也许这会有所帮助:
select * from products where id in
(
select max(id) as id from products
where sum(deleted) = 0
group by public_id
)
and online = 1
由Pentium10编辑
可以将查询重写为
SELECT *
FROM products p
JOIN (SELECT MAX(id) AS id
FROM products
HAVING SUM(deleted) = 0
GROUP BY public_id) d
ON d.id = p.id
WHERE online = 1
您需要索引:
答案 1 :(得分:0)
select * from products where public_id in
(
select public_id from products
group by public_id
having sum(deleted) = 0
)
and online = 1
尝试这项工作正常。子查询提供所有未删除的public_id,然后运行其他联机过滤器。
答案 2 :(得分:0)
这个有效吗,但我不知道它的效率。根据萨钦的回答
select p.* from products p where p.public_id in
(
select p2.public_id from products p2
group by p2.public_id
having sum(p2.deleted) = 0
)
and p.online = 1
and p.id = (select max(p3.id) from products p3 where p3.public_id = p.public_id);