如何使用第三个表连接两个不具有公共列的SQL表,第三个表包含这两个列

时间:2016-02-09 03:08:44

标签: mysql sql

我需要构建SQL查询以从meta表中获取所有用户元数据(signupidcourses_history表中。

问题是,signup表格没有user_iduser_logincourses_history只有user_id

还有第三个表格users,其中包含user_iduser_login,但我不知道如何以正确的方式连接所有3个表格

CREATE TABLE users
    (`user_id` int, `user_login` varchar(7), `description` varchar(55));

INSERT INTO users
    (`user_id`, `user_login`, `description`)
VALUES
    (100, 'user_1', 'userdataxxxx'),
    (201, 'user_2', 'userdatayyyy'),
    (301, 'user_3', 'userdatazzzz');

CREATE TABLE signups
    (`id` int, `user_login` varchar(7), `meta` varchar(55));

INSERT INTO signups
    (`id`, `user_login`, `meta`)
VALUES
    (1, 'user_1', 'metaxxxxx'),
    (2, 'user_2', 'metayyyy'),
    (3, 'user_3', 'metazzzzz');

CREATE TABLE courses_history
    (`id` int, `user_id` int, `stuff` varchar(55), `course_id` int);

INSERT INTO courses_history
    (`id`, `user_id`, `stuff`)
VALUES
    (1, 301, 'stuffxxx', 10),
    (2, 301, 'stuffyyyy', 11),
    (3, 100, 'stuffzzzz', 22);
    (4, 201, 'stuffzzzz', 66);
    (5, 201, 'stuffzzzz', 88);

由于

3 个答案:

答案 0 :(得分:1)

SELECT
    s.meta 
FROM
    signups AS s
    INNER JOIN courses_history AS ch
    ON s.id = ch.id
    INNER JOIN users AS u
    ON ch.user_id = u.user_id

你可以用这个来从所有三个表中提取你想要的任何数据,但我相信这说明了这一点。

答案 1 :(得分:1)

SELECT ch.id, u.user_login, su.meta
FROM signups su
INNER JOIN users u ON su.user_login = u.user_login 
INNER JOIN courses_history ch ON u.user_id = ch.user_id

答案 2 :(得分:0)

Select *
From 1st_table
Inner join CommonTable On common_field = 1stField
Inner join 2nd table on CommonField = 2ndfield