SQL:通过第三个链接密钥表从两个表中检索数据

时间:2015-09-16 00:13:47

标签: mysql sql sqlite

我有3张表如下:

CREATE TABLE "families" (
    "id_family" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
    "Family" TEXT
);
CREATE TABLE "levels" (
    "id_levels" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
    "Level" TEXT UNIQUE,
    "Description" TEXT
);
CREATE TABLE "level_families" (
    "id_levels" INTEGER REFERENCES "levels" ("id_levels"),
    "id_family" INTEGER REFERENCES "families" ("id_family")
);

INSERT INTO "families" ( "id_Family","Family" ) VALUES ( '1','Work' );
INSERT INTO "families" ( "id_Family","Family" ) VALUES ( '2','Hobbies' );
Insert Into "levels" ("id_levels", "level") Values ('1', 'Beginner');
Insert Into "levels" ("id_levels", "level") Values ('2', 'Elementary');
Insert Into "level_families" ("id_levels", "id_family") Values ('1', '1');
Insert Into "level_families" ("id_levels", "id_family") Values ('1', '2');
Insert Into "level_families" ("id_levels", "id_family") Values ('2', '2');

我正在尝试检索所有关联的系列级别,例如输出:

初学者:工作,爱好

小学:爱好

使用以下代码:

SELECT t.level, f.family
FROM families f
JOIN (
        SELECT lf.id_family, l.level
        FROM  level_families lf
                JOIN levels l
                ON lf.id_levels=l.id_levels
    ) t
ON f.id_family=t.id_family;

我得到了:

初学者:工作

初学者:爱好

小学:爱好

2 个答案:

答案 0 :(得分:0)

试试这个

event_items

答案 1 :(得分:0)

以下SQL检索了我想要的结果集,排序方面的小问题,但列中有数据。

Select Distinct
    levels.Level As Level,
    Group_Concat(families.Family, ', ') As Families
From
    levels Inner Join
    level_families On levels.id_levels = level_families.id_levels Inner Join
    families On families.id_family = level_families.id_family
Group By
    levels.Level

生成的数据

初学者:工作,爱好

小学:爱好