无法将年份与不同的表格字段进行比较

时间:2018-07-18 07:57:35

标签: mysql sql

我需要提取coach,其职业从特定的year到特定的team.id,这些是数据样本:

competition_seasons

| id | competition_id | season_id | name 
  22         48            14214    2017/2018

coach_career

| coach_id | team_id | start        | end
   223496      69       2018-07-01    NULL
   223496     4345      2011-10-01    2015-06-01
   223496    15376      2011-02-01    2011-10-01

在这种情况下,我需要提取coach = year(2017/2018)中包含的season.name 2018年开始的team.id的职业生涯69。

为此,我尝试了以下查询:

SELECT *
FROM coach_career cr
INNER JOIN coach c ON c.id = cr.coach_id
INNER JOIN competition_seasons s ON s.id = 22
WHERE cr.team_id = 69
AND `start` LIKE concat('%', cast(extract(year from s.name) as char(100)), '%')

但是这将返回一个空结果,我想我在提取年份时犯了一些错误,有人知道如何实现这一目标?

注意:表coachcoach_career的主表,仅包含人的信息。

2 个答案:

答案 0 :(得分:2)

您可以尝试此查询。

因为您使用like来使用colnum,所以||而不是concat

然后将开始LIKE '%' || s.name || '%'条件移到ON的{​​{1}},因为JOIN将返回所有比赛。

INNER JOIN competition_seasons s ON s.id = 22

sqlfiddle

[结果]

SELECT *
FROM coach_career cr
INNER JOIN coach c ON c.id = cr.coach_id
INNER JOIN competition_seasons s ON `start` LIKE '%' || s.name || '%'
WHERE  
  s.id = 22 
and 
  cr.team_id = 69

答案 1 :(得分:1)

您可以尝试以下代码。它使用locate()功能来检查季节name中是否包括开始职业的年份。

样本数据:

create table competition_seasons(id int, competition_id int, season_id int, name varchar(10));
insert into competition_seasons values (22, 48, 14214, '2017/2018');
create table coach_career(coach_id int, team_id int, `start` date, `end` date);
insert into coach_career values
(223496, 69, '2018-07-01', NULL),
(223496, 4345, '2011-10-01', '2015-06-01'),
(223496, 15376, '2011-02-01', '2011-10-01');

T-SQL:

select * from coach_career cc
where exists(select 1 from competition_seasons
             where locate(year(cc.start), name) > 0);