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)
我做错了什么?
答案 0 :(得分:1)
只需添加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
答案 1 :(得分:0)
如果您使用相同的订单获得相同的结果,请按以下步骤添加“group by a.id”广告:
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