mysql将两个额外的列连接到查询中

时间:2013-11-23 11:02:08

标签: mysql sql join

我有以下的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

1 个答案:

答案 0 :(得分:1)

你想要

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