【问题标题】:sql clauses using HAVING truncated value error for part of the string对部分字符串使用 HAVING 截断值错误的 sql 子句
【发布时间】:2020-08-17 20:36:08
【问题描述】:

我收到一个整数值错误,但不明白为什么。

警告:#1292 截断不正确的 INTEGER 值:'%accepted%';

警告:#1292 截断不正确的 INTEGER 值:'%pending%'。

它没有处理错误。 “第 1 位”中的任何内容都没有错误。

有人可以帮忙吗?

SELECT a.`post_id`, b.`name`,
       MAX(case when meta_key = 'value' THEN `meta_value` ELSE NULL END) as  'Email',
FROM table_1 a

INNER JOIN table_2 b
ON FIND_IN_SET(a.post_id, b.payment_ids)
GROUP BY a.post_id
HAVING OrderStatus LIKE '%processing%' OR '%pending%' OR '%accepted%' AND DeliveryDate >= (DATE_SUB(CURDATE(), INTERVAL 7 DAY)) AND DeliveryType = 'pickup'

【问题讨论】:

  • 您不能只使用 OR 值。你需要有完整的陈述,所以OrderStatus like ... OR OrderStatus like ...
  • 啊,非常感谢。

标签: mysql sql where-clause sql-like having-clause


【解决方案1】:

OrderStatus LIKE '%processing%' OR '%pending%' OR '%accepted%'

这并不像你想的那样。 MySQL 将其理解为:

(OrderStatus LIKE '%processing%')
OR ('%pending%')
OR ('%accepted%')

因此它尝试在布尔上下文中评估字符串,这会产生您收到的警告。

您需要为每个匹配的字符串重复 like 表达式:

(
    OrderStatus LIKE '%processing%' 
    OR OrderStatus LIKE '%pending%' 
    OR OrderStatus LIKE '%accepted%'
)

或者你可以使用正则表达式:

OrderStatus RLIKE 'processing|pending|accepted'

请注意,这些条件应属于where 子句而不是having 子句,因为它们与非聚合列相关。我会将查询表述为:

select
    t1.post_id,
    t2.name,
    -- no need for an "else" branch here
    max(case when meta_key = 'value' then meta_value end) as email 
from table_1 t1
inner join table_2 t2 on find_in_set(t1.post_id, t2.payment_ids)
where
-- filtering in the "where" clause
    OrderStatus rlike 'processing|pending|accepted'    -- regex
    and DeliveryDate >= current_date - interval 7 day  -- no need for "datesub()"
    and DeliveryType = 'pickup'
group by 
-- all non-aggregated column in the `group by` clause    
    t1.post_id, 
    t2.name  

请注意,您应该在查询中的 all 列前加上它们所属的表,以使代码明确且不言自明。

【讨论】:

  • 谢谢 我被告知我不能使用 WHERE 子句,当我尝试它时会产生错误。是的,我确实把它放在了正确的地方。它只会提供一个空的结果集
  • 在继续播放时会提供警告:#1292 截断不正确的日期值:'DeliveryDate',同时发布一个空的结果集。以前我曾经有 WHERE 子句,但在这篇文章中得到了更正 - [link]stackoverflow.com/questions/63432930/… [link]
  • @Tim:这不是来自我给你的查询。但很可能,您在列名 DeliveryDate 周围有不应该存在的单引号。
  • 正确。如果我没有引号,我会收到错误 #1054 - 'where 子句'中的未知列 'DeliveryType'
  • 正确。如果我没有引号,我会收到错误 #1054 - 'where 子句'中的未知列 'DeliveryType' – Tim
【解决方案2】:
SELECT a.`post_id`, b.`name`,
       MAX(case when meta_key = 'value' THEN `meta_value` ELSE NULL END) as  'Email',
FROM table_1 a

INNER JOIN table_2 b
ON FIND_IN_SET(a.post_id, b.payment_ids)
GROUP BY a.post_id
HAVING OrderStatus LIKE '%processing%' OR OrderStatus LIKE '%pending%' OR OrderStatus LIKE '%accepted%' AND DeliveryDate >= (DATE_SUB(CURDATE(), INTERVAL 7 DAY)) AND DeliveryType = 'pickup'

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2013-06-29
    • 2017-08-02
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多