LIKE 运算符无法正常使用日期

Posted

技术标签:

【中文标题】LIKE 运算符无法正常使用日期【英文标题】:LIKE operator not working properly with date 【发布时间】:2018-07-03 12:46:29 【问题描述】:

我正在尝试返回包含日期年份的记录,让我解释一下,这是我的查询:

$query = "SELECT coach.*
  FROM coach_career coach_cr
  LEFT JOIN coach coach ON coach.id = coach_cr.coach_id
  LEFT JOIN competition_seasons s ON s.id = :season_id
  WHERE coach_cr.team_id = 95 AND `start` LIKE '%2017/2018%'";

我需要选择coach_career上的所有coach字段,一个coach可以在不同的seasons中训练不同的团队,所以我需要接受具有season.name2017/2018的教练,但 start 日期的日期时间格式如下:2017-01-01

我该如何处理这种情况?

样本数据

教练:

id | name | last_name
 1   foo      test

教练生涯:

coach_id | team_id | start       | end
   1         95       2017-01-01   NULL

competition_seasons

id | name | 
1    2017/2018

【问题讨论】:

样本数据和期望的结果真的很有帮助。 @GordonLinoff 检查我的更新 如果start 是日期,则使用start >= '2017-01-01' AND start < '2019-01-01' @SalmanA 问题不是开始字段,问题是 s.name 不是日期并且包含 2017/2018 如果你使用'2017/2018' like '%' + convert(varchar(10), datepart(year, [start])) + '%'而不是[start] like '%2017/2018%'会解决你的问题吗? 【参考方案1】:

您可以使用BETWEEN 关键字。

$query = "SELECT coach.*
      FROM coach_career coach_cr
      LEFT JOIN coach coach ON coach.id = coach_cr.coach_id
      LEFT JOIN competition_seasons s ON s.id = :season_id
      WHERE coach_cr.team_id = 95 AND `start` BETWEEN '2017-01-01' and '2018-12-31'";

【讨论】:

s.name 的值是2017/2018%,正如我在查询中所写的那样,所以不是2017/2018% 认为那是s.name,我不能在两者之间使用.. 你能用:` WHERE coach_cr.team_id = 95 AND (s.name like '%2017%' OR s.name like '%2018%')`【参考方案2】:

抱歉,我的答案是针对 SQL Server。这是修正后的版本:

create table coach(id integer, name char(100));
insert into coach(id, name) values(1, 'Jack'), (2, 'Peter');

create table coach_career (coach_id integer, season_id integer, start date, end date);
insert into coach_career values (1, 95, '20170101', null), (2, 95, '20010101', null);

create table competition_seasons (id integer, name char(100));
insert into competition_seasons values (95, '2017/2018');

SELECT coach.*
FROM coach_career cc
LEFT JOIN coach ON coach.id = cc.coach_id
LEFT JOIN competition_seasons s ON s.id = cc.season_id
WHERE cc.season_id = 95 
      AND '2017/2018' like concat('%', cast(extract(year from cc.start) as char(100)), '%');

【讨论】:

感谢您的回复,很遗憾您的查询返回空结果... 这很奇怪,我在paiza.io/projects/SdtzcJ0SoUfg1QS7k3I8QQ?language=mysql 上测试过,它返回Jack【参考方案3】:

试试这个

$query = "SELECT coach.*
    FROM coach_career coach_cr
    LEFT JOIN coach coach 
        ON coach.id = coach_cr.coach_id
    LEFT JOIN competition_seasons s
        ON s.id = :season_id
    WHERE coach_cr.team_id = 95 
        AND `start` LIKE '%2017%' 
        OR LIKE '%2018%'";

【讨论】:

以上是关于LIKE 运算符无法正常使用日期的主要内容,如果未能解决你的问题,请参考以下文章

BigQuery - 将正则表达式与 LIKE 运算符 (?) 结合使用

带有 LIKE 运算符的 Select 语句中的 MySQL 案例

LIKE运算符

如何在 laravel 的 eloquent 中转换表列数据?

SQL学习——LIKE运算符

如何使用多个 LIKE 运算符和使用索引