简体   繁体   中英

Grouping rows in sqlite not working as expected

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)

So I want to group all articles with same title:

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

But I want this:

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

What am I doing wrong?

Just add a group by clause.

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

yo get the same results with the same order, add the "group by a.id" ad follows:

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.id

Demo here: http://sqlfiddle.com/#!7/d1ccf/11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM