LIKE运算子无法正确处理日期

时间:2018-07-03 12:46:30

标签: mysql sql pdo

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

$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上的所有coach_career字段,一个coach可以在不同的seasons训练不同的团队,所以我需要聘请具备以下条件的教练season.name的值为2017/2018,但start日期的日期时间格式为:2017-01-01

如何处理这种情况?

样本数据

教练:

id | name | last_name
 1   foo      test

coach_career:

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

competition_seasons

id | name | 
1    2017/2018

3 个答案:

答案 0 :(得分: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'";

答案 1 :(得分:0)

尝试这个

$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%'";

答案 2 :(得分:0)

对不起,我的答案是针对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)), '%');