开发者

Aggregate joined table results in an SQL SELECT on MySQL 5

I have the following schema, and would like to do a query that returns one row for each entry in the articles table, with it's corresponding content column from the content table, and a column with each of that articles tags, such as you might get by using concat.

The query should SELECT only rows that match a certain tag. So if the tag atdi was provided, the result set would look something like:

id    content                                                tags
1     on my way nails broke and fell                         song,atdi,invalid
3     im all alone so far up here and my oxygen is all gone  song,atdi,hourglass
4     you know your insides true better than i do            song,atdi,starslight

I've tried a few different ways with subqueries, but keep getting errors - it's quite frustrating.

Here's the schema:

CREATE TABLE articles (
id int not null default 0,
published datetime,
author int not null default 0,
primary key (id)
);

INSERT INTO articles
(id, published, author)
VALUES
(1, CURRENT_TIMESTAMP, 1),
(2, CURRENT_TIMESTAMP, 1),
(3, CURRENT_TIMESTAMP, 1),
(4, CURRENT_TIMESTAMP, 1);

CREATE TABLE content (
id int not null d开发者_运维问答efault 0,
content varchar(250) not null default '',
primary key (id)
);

INSERT INTO content
(id,content)
VALUES
(1,'on my way nails broke and fell'),
(2,'exo skeleton junction at the railroad delayed'),
(3,'im all alone so far up here and my oxygen is all gone'),
(4,'you know your insides true better than i do');

CREATE TABLE tags (
id int not null default 0,
tag varchar(100) not null default '',
primary key (id,tag)
);

INSERT INTO tags
(id,tag)
VALUES
(1,"song"),
(2,"song"),
(3,"song"),
(4,"song"),
(1,"atdi"),
(2,"mars"),
(3,"atdi"),
(4,"atdi"),
(1,"invalid"),
(2,"roulette"),
(3,"hourglass"),
(4,"starslight");


Try something like this one

select a.id, a.content, b.tags_1 
from content as a  inner join (
    select id, GROUP_CONCAT(tag SEPARATOR ',') as tags_1 FROM tags group by id
) as b on a.id = b.id 
INNER JOIN tags AS c ON a.id = c.id
WHERE c.tag = 'atdi'

Using the GROUP_CONCAT() method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜