根据if语句选择视图中的2列之一

时间:2015-12-16 08:21:36

标签: mysql sql

我有一个足球比赛表,我们有2列:第1队和第2队 在另一个表中,我有团队表: 所以,

 If teams.name = Team1.name => Team2.name is Away Game
If teams.name = Team2.name => Team2.name is Home Game.

我认为这个观点在网上课程中正常工作,我无法编辑它:

CREATE 
VIEW `additional_time_goals` AS
    SELECT 
        `p`.`team` AS `Team`,
        `p`.`player_name` AS `Player`,
        `p`.`Round` AS `Round`,
        `p`.`time` AS `time`,
        `p`.`extra_time` AS `Extra Time`,
        `m`.`Team 1` AS `Team 1`,
        `m`.`Team 2` AS `Team 2`
    FROM
        (`players_scored` `p`
        JOIN `matches` `m` ON ((((`p`.`team` = `m`.`Team 1`)
            OR (`p`.`team` = `m`.`Team 2`))
            AND (`p`.`Round` = `m`.`Round`)
            AND (`p`.`extra_time` IS NOT NULL))))

因此,我不想选择Team 1和Team 2这两个列,而是想看看p.team = team 1是否会显示Team 2,反之亦然。

2 个答案:

答案 0 :(得分:3)

我不确定,但我认为这可能有助于你

CREATE 
VIEW `additional_time_goals` AS
    SELECT 
        `p`.`team` AS `Team`,
        `p`.`player_name` AS `Player`,
        `p`.`Round` AS `Round`,
        `p`.`time` AS `time`,
        `p`.`extra_time` AS `Extra Time`,
        `m`.`Team 1` AS `Team 1`,
        `m`.`Team 2` AS `Team 2`,
    CASE WHEN p.team = team 1 THEN team 2
         WHEN p.team = team 2 THEN team 1
         ELSE '' as val
    FROM
        (`players_scored` `p`
        JOIN `matches` `m` ON ((((`p`.`team` = `m`.`Team 1`)
            OR (`p`.`team` = `m`.`Team 2`))
            AND (`p`.`Round` = `m`.`Round`)
            AND (`p`.`extra_time` IS NOT NULL))))

答案 1 :(得分:2)

您正在寻找CASE WHEN。我进一步建议摆脱所有那些使你的标准难以阅读的范例。并考虑使用简单的列名(例如team1而不是" Team 1"由于空格字符,您总是需要引用)。

create view additional_time_goals as
  select 
    p.team,
    p.player_name as player,
    p.round,
    p.time,
    p.extra_time as "extra time",
    p.team as team_a,
    case when p.team = m."Team 1" then m."Team 2" else m."Team 1" end as team_b
  from players_scored p
  join matches m on p.team in (m."Team 1", m."Team 2")
                 and p.round = m.round
                 and p.extra_time is not null;