简体   繁体   中英

error with sql syntax where having

Just trying to make this query work, but it is a bit difficult for me..

SELECT
    *, 
  COUNT(*) AS total FROM_UNIXTIME(consume_time,'%Y-%m') AS fecha
FROM
    coupon
HAVING
    fecha = '2016-07'
GROUP BY
    partner_id
  1. You're missing a , in the select list, between AS total and FROM_UNIXTIME .

  2. HAVING filters grouped sets, whereas WHERE filters records before they are grouped—in this case you want the latter, however aliases like fecha are not available when the WHERE clause is evaluated. You therefore need to repeat the underlying expression in the WHERE clause:

     WHERE FROM_UNIXTIME(consume_time,'%Y-%m') = '2016-07' 

    However, this approach would not be sargable—better to convert your literal to a range upon which consume_time can be directly filtered (especially if the table has an index thereon):

     WHERE consume_time >= UNIX_TIMESTAMP('2016-07-01') AND consume_time < UNIX_TIMESTAMP('2016-08-01') 

    Even better still to store consume_time as a temporal datatype that MySQL understands, eg TIMESTAMP (which happens to be stored internally as a Unix timestamp), rather than a mere integer—then you'd be able to do away with the conversion functions altogether:

     WHERE consume_time >= '2016-07-01' AND consume_time < '2016-08-01' 
  3. Since you're grouping by partner_id , the values in any resultset column that are not functionally dependent thereon will be indeterminate. This probably is not what you want. Did you really mean to select all columns but group by partner_id ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM