我有一个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,然后我可以用它来加入团队表。有人能指出我正确的方向来修复这个错误吗?提前谢谢。
答案 0 :(得分: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
答案 1 :(得分: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类,但具有我需要的相同功能。
由于
Doniani