2014-12-04 77 views
0

我需要一个mysql查询,它将选择“name”或“quantity”列中包含“joe”的所有行。它需要之间的“名”与“量”的栏目,这意味着我们将得到数量与每名corressponding如下面的图像的最大值不同: enter image description here用SQL中的distinct和max查询

决赛桌也应由排序id降序。 请告诉我知道用mysql查询的方式。 感谢

+0

可能下一个字符串出现在整数列什么情况? – Strawberry 2014-12-04 08:26:31

回答

0

最简单的方法是使用not exists

select * from table_name t1 
where 
not exists (
select 1 from table_name t2 where t1.name= t2.name and t1.quantity < t2.quantity 
); 

另一个变化是使用left join

select t1.* from table_name t1 
left join table_name t2 on t2.name = t1.name 
and t1.quantity < t2.quantity 
where t2.id is null; 
+0

而最快的方式是...(选项3) – Strawberry 2014-12-04 08:28:12

+0

那么左边的连接性能好于存在索引列时的情况。优化器可以针对一小部分数据进行优化,而当表格相对较小且编制索引时,它们之间没有区别。如果你知道更快的方式,为什么不把它作为答案而不是评论? – 2014-12-04 08:38:28

+0

因为在手机上打字很乏味,所以我想你可能知道我所指的方法。毕竟它已经在手册中涵盖了。 – Strawberry 2014-12-04 08:46:44