【问题标题】:LIKE operator not working properly with dateLIKE 运算符无法正常使用日期
【发布时间】: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%'会解决你的问题吗?

标签: mysql sql pdo


【解决方案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)), '%');

【讨论】:

【解决方案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%'";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2015-11-27
    • 2015-04-25
    相关资源
    最近更新 更多