mysql concat和where子句中的子字符串索引

l3zydbqr  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(352)

我在表中选择了一个值,其格式如下:

day_shared =
    12_month
    3_month
    1_week

我需要使用这个函数在date\u add()中,这是我到目前为止的代码,但它似乎出错了,我不知道我做错了什么。非常感谢您的帮助/建议

WHERE
    NOW() <  DATE_ADD(date_posted, INTERVAL CONCAT(CONVERT(SUBSTRING_INDEX(day_shared,'_', 1), SIGNED INTEGER),' ',UPPER(SUBSTRING_INDEX(day_shared,'_', -1))))

gordon尝试的解决方案:

NOW() < DATE_ADD(
  date_posted, 
  (
    CASE WHEN day_shared LIKE '%_week' THEN INTERVAL (
      SUBSTRING_INDEX(day_shared , '_', 1) + 0
    ) WEEK WHEN day_shared  LIKE '%_month' SUBSTRING_INDEX(day_shared , '_', 1) + 0 DAY THEN INTERVAL (
      SUBSTRING_INDEX(day_shared , '_', 1) + 0
    ) MONTH END
  )
) 

Something is wrong in your syntax '(
  CASE WHEN day_shared LIKE '%_week' THEN INTERVAL (
    SUBSTRING' on line 8
smdncfj3

smdncfj31#

NOW()
<
CASE
  WHEN day_shared LIKE '%_week'
    THEN
      DATE_ADD(
        date_posted,
        INTERVAL (SUBSTRING_INDEX(day_shared , '_', 1) + 0) WEEK
      )
  WHEN day_shared LIKE '%_month'
    THEN
      DATE_ADD(
        date_posted,
        INTERVAL (SUBSTRING_INDEX(day_shared , '_', 1) + 0) MONTH
      )
END
vx6bjr1n

vx6bjr1n2#

问题是 dayinterval 1 day 是sql关键字,不是字符串。所以不能从列名解析它。
所以,你可以用 CASE 用于处理不同时间单位的表达式:

WHERE  NOW() <  (CASE WHEN day_shared LIKE '%_day'
                      THEN date_posted + INTERVAL (SUBSTRING_INDEX(day_shared, '_', 1) + 0) DAY
                      WHEN day_shared LIKE '%_week'
                      THEN date_posted + INTERVAL (SUBSTRING_INDEX(day_shared, '_', 1) + 0) WEEK
                      WHEN day_shared LIKE '%_month'
                      THEN date_posted + INTERVAL (SUBSTRING_INDEX(day_shared, '_', 1) + 0) MONTH
                  END)

这种语法有效。

相关问题