CREATE TABLE Article(
    ID INTEGER NOT NULL,
    Title TEXT
);
CREATE TABLE Tag(
    ID INTEGER NOT NULL,
    Name TEXT
);
CREATE TABLE Article_Tag(
    Article_ID INTEGER NOT NULL,
    Tag_ID INTEGER NOT NULL,
    PRIMARY KEY (Article_ID,Tag_ID)
);
INSERT INTO Article (ID, Title) VALUES
(1,  'wifi'),
(2,  'bluetooth'),
(3,  'firewire');
INSERT INTO Tag (ID, Name) VALUES
(1,  'tag 1'),
(2,  'tag 2'),
(3,  'tag 3');
INSERT INTO Article_Tag (Article_ID, Tag_ID) VALUES
(1,  1),
(1,  2),
(1,  3),
(2,  1);
--------------------------------------
SELECT
  a.Title,
  t.Name AS TagName
FROM Article AS a
  LEFT OUTER JOIN Article_Tag AS a_t ON a.ID = a_t.Article_ID
  LEFT OUTER JOIN Tag t ON t.ID = a_t.Tag_ID
--------------------------------------
Title           TagName
wifi            tag 1
wifi            tag 2
wifi            tag 3
bluetooth       tag 1
firewire        (null)


所以我想对所有标题相同的文章进行分组:

SELECT
  a.Title,
  GROUP_CONCAT(t.Name,';') AS TagNames
FROM Article AS a
  LEFT OUTER JOIN Article_Tag AS a_t ON a.ID = a_t.Article_ID
  LEFT OUTER JOIN Tag t ON t.ID = a_t.Tag_ID
--------------------------------------
Title       TagNames
firewire    tag 1;tag 2;tag 3;tag 1


但是我想要这个:

Title       TagNames
wifi        tag 1; tag 2; tag3
bluetooth   tag 1;
firewire    (null)


我究竟做错了什么?

最佳答案

只需添加一个group by子句。

SELECT
  a.Title,
  GROUP_CONCAT(t.Name,';') AS TagNames
FROM Article AS a
  LEFT OUTER JOIN Article_Tag AS a_t ON a.ID = a_t.Article_ID
  LEFT OUTER JOIN Tag t ON t.ID = a_t.Tag_ID
group by a.title

关于sql - 在sqlite中对行进行分组无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34800954/

10-11 14:06