开发者

Can I use a field as the 'unit' in TIMESTAMPDIFF?

This is a followup to a another question, but I think warrants its own question:

Can I use a field as the 'unit' parameter in TIMESTAMPDIFF()?

For example, here's a snippet:

SELECT foo FROM table t LEFT JOIN frequencies f USING (frequency_id)
WHERE MOD(TIMESTAMPDIFF(f.frequenc开发者_开发知识库y_code, t.date, NOW()), t.frequency_num) = 0

This gets a syntax error when I run it. Now, if I replace f.frequency_code with an actual word - MINUTE, DAY, etc. - it works. But those are exactly the words currently contained in f.frequency_code.

Is it simply not doable to be able to use a table field in that location?


TIMESTAMPDIFF() does not support dynamic units like that.

Since you're working with a known set of units, you could use a CASE statement to achieve this.

Starting with your example query, something like this would probably work:

SELECT foo 
FROM table t 
LEFT JOIN frequencies f USING (frequency_id)
WHERE MOD(
(CASE 
  WHEN f.frequency_code = 'MICROSECOND' THEN TIMESTAMPDIFF(MICROSECOND, t.date, NOW())
  WHEN f.frequency_code = 'SECOND' THEN TIMESTAMPDIFF(SECOND, t.date, NOW())
  WHEN f.frequency_code = 'MINUTE' THEN TIMESTAMPDIFF(MINUTE, t.date, NOW())
  WHEN f.frequency_code = 'HOUR' THEN TIMESTAMPDIFF(HOUR, t.date, NOW())
  WHEN f.frequency_code = 'DAY' THEN TIMESTAMPDIFF(DAY, t.date, NOW())
  WHEN f.frequency_code = 'WEEK' THEN TIMESTAMPDIFF(WEEK, t.date, NOW())
  WHEN f.frequency_code = 'MONTH' THEN TIMESTAMPDIFF(MONTH, t.date, NOW())
  WHEN f.frequency_code = 'QUARTER' THEN TIMESTAMPDIFF(QUARTER, t.date, NOW())
  WHEN f.frequency_code = 'YEAR' THEN TIMESTAMPDIFF(YEAR, t.date, NOW())
  END)
, t.frequency_num) = 0


Not 100%, but you might manage to work around the issue by creating a function that prepares and executes dynamic sql.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜