0

我有一个 MySQL 查询问题。我建立了一个记录高中橄榄球分数的表格。它看起来像这样:

CREATE TABLE `games` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `home_team` int(11) NOT NULL,
  `visitor_team` int(11) NOT NULL,
  `home_score` tinyint(4) NOT NULL,
  `visitor_score` tinyint(4) NOT NULL,
  `quarter` tinyint(4) NOT NULL,
  `week` tinyint(2) NOT NULL,
  `game_date` date NOT NULL,
  `game_time` time NOT NULL,
  `complete` tinyint(4) NOT NULL DEFAULT '0',
  `stadium_id` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=151;

我正在执行的查询使用团队的 id 进行比较。我想检索给定团队 id 仅击败的团队的 id 值。到目前为止,这是我的查询。

SELECT 
    CASE 
        WHEN games.home_team != ? AND (games.home_score > games.visitor_score) THEN games.home_team 
        WHEN games.visitor_team != ? AND (games.home_score < games.visitor_score) THEN games.visitor_team 
    END AS id, teams.class_id, classes.name 
FROM games 
    INNER JOIN teams ON id = teams.id 
    INNER JOIN classes ON teams.class_id = class.id
    WHERE games.complete = 1

当我在 PHP MyAdmin 中运行此查询时,我收到以下错误:

#1052 - Column 'id' in on clause is ambiguous

我正在使用 PDO 的 execute(),所以 ? 代表团队 id 值。我想既然我将 CASE 语句的结果分配给了 id,那么我可以使用它来加入团队表。谁能指出我正确的方向来解决这个错误?先感谢您。

4

2 回答 2

3

您需要使用多个表中存在的列前面的表名,或使用别名:

INNER JOIN teams ON games.id = teams.id 

编辑:话虽如此,它似乎实际上是一个列别名,你不能这样做:

INNER JOIN teams ON
CASE 
    WHEN games.home_team != ? AND (games.home_score > games.visitor_score) THEN games.home_team 
    WHEN games.visitor_team != ? AND (games.home_score < games.visitor_score) THEN games.visitor_team 
END  = teams.id 

您也可以先使用子查询,然后在没有额外 case 语句的情况下匹配结果。

Select
    sub.id,
    teams.class_id,
    classes.name
from
    (
        SELECT 
            CASE 
            WHEN games.home_team != ? AND (games.home_score > games.visitor_score) THEN games.home_team 
            WHEN games.visitor_team != ? AND (games.home_score < games.visitor_score) THEN games.visitor_team 
            END AS id
        FROM 
            games
        WHERE 
            games.complete = 1
    ) sub
    INNER JOIN teams ON sub.id = teams.id 
    INNER JOIN classes ON teams.class_id = class.id
于 2013-10-29T00:45:37.460 回答
0

我做了一个简单的函数来实现它。它的工作。

// get variable
$area = $_GET['area'];

// function
function cases($a) {

    $sel_dash = mysql_query("SELECT * FROM sys_dash WHERE area = '$a'");
    $dados = mysql_fetch_assoc($sel_dash);
    $page = $dados['page'];

    return $page;
}

// call function with the variable
$page = cases($area);

要测试您得到的值是否正确,您可以将“return”更改为“echo”,变量将写入代码中。

我使用的表格是:

CREATE TABLE `sys_dash` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `area` VARCHAR(250) NOT NULL,
    `page` VARCHAR(250) NOT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT

我希望我能帮上忙!

它注意到 PHP 的 CASE 类,但具有我需要的相同功能。

谢谢

多尼亚尼

于 2016-04-04T14:37:16.653 回答