将子数据存储在单列中

时间:2017-10-24 20:16:50

标签: sqlite parent-child hierarchical-data

我有以下表格:

 CREATE TABLE titles (
     id INTEGER,
     title VARCHAR(255)
   );
   INSERT INTO titles (id, title) VALUES (1, "Mars Attacks!");
   INSERT INTO titles (id, title) VALUES (2, "Da Vinci Code");

   CREATE TABLE GenreName (
     id INTEGER,
     name VARCHAR(255)
   );

   INSERT INTO GenreName (id, name) VALUES (1, "Action");
   INSERT INTO GenreName (id, name) VALUES (2, "Adventure");
   INSERT INTO GenreName (id, name) VALUES (3, "Comedy");
   INSERT INTO GenreName (id, name) VALUES (4, "Science-Fiction");
   INSERT INTO GenreName (id, name) VALUES (5, "Thriller");

   CREATE TABLE Genre (
     title INTEGER,
     genre INTEGER
   );
   INSERT INTO Genre (title, genre) VALUES (1, 1);
   INSERT INTO Genre (title, genre) VALUES (1, 3);
   INSERT INTO Genre (title, genre) VALUES (1, 4);
   INSERT INTO Genre (title, genre) VALUES (2, 1);
   INSERT INTO Genre (title, genre) VALUES (2, 5);

我正在寻找一种检索数据的方法

Id            Title                  Genre
1             Mars Attacks!          Action, Comedy, Science-Fiction
2             Da Vinci Code          Action, Thriller

我坚持选择数据的递归方式。

我有DBFiddle

2 个答案:

答案 0 :(得分:0)

使用SQL OUTER JOINS

select titles.id, name, title from titles left outer join genre on titles.id = genre.title left outer join genrename on genre.genre = genrename.id;

答案 1 :(得分:0)

选择t.id,t.title,group_concat(gn.name)from genere g join titles t on t.id = g.title join genrename gn on gn.id = g.genre group by t.id,t .title伪