【问题标题】:MySQL Substring with WHERE带有 WHERE 的 MySQL 子字符串
【发布时间】:2014-01-20 19:27:54
【问题描述】:

我在互联网上进行了搜索,但找不到解决问题的方法。我的查询是这样的

SELECT users.id, SUBSTRING(posts.datestr, 4, 8) 
FROM users, posts 
WHERE posts.datestr='Jan-2014'

(上面的查询被缩短了)

posts.datestr 中的值实际上是20-Jan-2014,但我希望它改为Jan-2014,但即使添加了SUBSTRING 代码,它仍然以某种方式显示为20-Jan-2014

知道我做错了什么吗?

谢谢!

【问题讨论】:

  • datestr 是 varchar 吗?如果是,为什么不使用数据类型?
  • 试试这个SELECT * FROM table WHERE YEAR(Date) = 2014 AND MONTH(Date) = 1"
  • 我的 datestr 是一个 varchar,这还能用吗?
  • 真的,将数据和列转换为DATE 数据类型,您的问题会容易得多,解决起来也很简单。

标签: mysql sql select substring date-format


【解决方案1】:

您需要为SUBSTRING 的结果设置别名,并在您的条件中使用该别名(以下示例中的shortdate

由于您现在将在条件中使用别名,因此您不能使用 where 子句,但可以使用 having 子句

类似:

SELECT users.id, SUBSTRING(posts.datestr, 4, 8) as shortdate 
FROM users, posts 
HAVING shortdate='Jan-2014'

【讨论】:

    【解决方案2】:
    SELECT users.id, SUBSTRING(posts.datestr, 4, 8) shortpostdate FROM users, posts WHERE shortpostdate='Jan-2014'
    

    【讨论】:

      【解决方案3】:

      使用Inner JOIN

      SELECT users.id, SUBSTRING(posts.datestr, 4, 8) FROM users inner join posts on users.userid = posts.[primary key] WHERE posts.datestr='Jan-2014'
      

      下面的链接可以帮助你http://www.w3schools.com/sql/sql_join_inner.asp

      【讨论】:

        【解决方案4】:

        使用下面的

        substr(posts.datestr,3)
        

        而不是

         SUBSTRING(posts.datestr, 4, 8)
        

        【讨论】:

          【解决方案5】:

          使用DATETIME 函数代替SUBSTRING()

          SELECT users.id, DATE_FORMAT(STR_TO_DATE(posts.datestr, '%d-%b-%Y'), '%b-%Y') updatedDate
          FROM users, posts 
          HAVING updatedDate = 'Jan-2014'
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-28
            • 2013-03-19
            • 1970-01-01
            • 2015-05-28
            相关资源
            最近更新 更多