如何从mysql中的select语句返回的多列中选择一列

时间:2015-10-18 16:57:21

标签: mysql sql mysql-workbench

我想从select语句中的多列中只选择一列。

select 
    A, sum(B) paid
from
   T
where
    K LIKE '2015%'
group by A
having B >= 100

此查询将返回两列,但如何仅从select查询中选择第一列?如果我做这样的事情:

select A from (select 
    A, sum(B) paid
from
   T
where
    K LIKE '2015%'
group by A
having B >= 100 ) 

遇到错误?有没有办法在mysql中选择唯一的第一列?

4 个答案:

答案 0 :(得分:1)

您可以选择以下两种方法之一:

select A from (
  select A, sum(B) paid from T where K LIKE '2015%'
 group by A having sum(B) >= 100
) m

两个

select A from T where K like '2015%' group by A having sum(B)>=100

答案 1 :(得分:1)

你只想要你说。

select distinct A 
from T 
where k like '2015%' and B >= 100
顺便说一句,我们不知道k是什么数据类型(即:见戈登的评论)

日期/日期时间的Mysql year function

所以它会是year(k)=2015

答案 2 :(得分:1)

您的第二个查询是正确的,因为您没有在sum

之前添加b

试试这个

select A from (select 
    A, sum(B) paid
from
   T
where
    K LIKE '2015%'
group by A
having sum(B) >= 100 ) As temp

答案 3 :(得分:1)

我猜K是个约会对象。您不应该使用like作为日期。编写查询的最佳方法是:

select A
from T
where K >= '2015-01-01' and K < '2016-01-01'
group by A
having sum(B) >= 100;

这可以利用T(K, A, B)上的索引。