我有下面的SQL。
CREATE TABLE states (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
CREATE TABLE teams (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
stateid INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
CREATE TABLE debates (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
debatedate DATE NOT NULL,
hostid INT,
visitid INT,
winnerid INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
INSERT INTO states (id, name) VALUES
(1,'New York'),
(2,'Pennsylvania'),
(3,'Ohio');
INSERT INTO teams (id, name, stateid) VALUES
(1,'team one',1),
(2,'team two',2),
(3,'team three',2),
(4,'team four',1),
(5,'team five',2),
(6,'team six',3);
INSERT INTO debates (id, debatedate,hostid, visitid, winnerid ) VALUES
(1,'2012-01-11', 1,2,1),
(2,'2012-01-11', 3,4,4),
(3,'2012-02-11', 5,6,5),
(4,'2012-02-11', 1,4,1),
(5,'2012-02-11', 2,5,5),
(6,'2012-02-11', 3,6,3),
(7,'2012-03-11', 6,1,1),
(8,'2012-03-11', 5,2,5),
(9,'2012-03-11', 3,4,4);
SELECT deb.id, t1.name as Visitor , t2.name as Host
FROM debates AS deb
INNER JOIN teams t1 ON t1.id = deb.visitid
INNER JOIN teams t2 ON t2.id = deb.hostid
GROUP BY id
LIMIT 1 --Just have limit 1 to save space in the question
哪个返回
-----------------------------
|ID |VISITOR |HOST |
|1 |team two |team one |
-----------------------------
我也想返回辩论所处的状态。
答案将是hostid的状态。
在teams表中有一个stateid列,但是我在使用它时遇到了麻烦。
我试图添加联接
INNER JOIN teams t3 ON t3.id = states.id
但是我得到了错误
Unknown column 'states.id' in 'on clause'
我将如何获取此信息。
我想回来
-----------------------------------------
|ID |VISITOR |HOST |State |
|1 |team two |team one |New York |
-----------------------------------------
see fiddle
最佳答案
你要
SELECT deb.id, t1.name as Visitor , t2.name as Host, s.name
FROM debates AS deb
INNER JOIN teams t1 ON t1.id = deb.visitid
INNER JOIN teams t2 ON t2.id = deb.hostid
inner join states s on t2.stateid = s.id
GROUP BY id
关于mysql - mysql将另外两列加入查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20161496/