mysql - 聚合联接表导致 MySQL 5 上的 SQL SELECT

标签 mysql sql join

我有以下架构,并且想执行一个查询,为 articles 表中的每个条目返回一行,它对应 contentcontent 表,以及包含每个文章标签的列,例如您可以使用 concat 获得的标签。

查询应该只选择与特定标记匹配的行。因此,如果提供了标签 atdi,结果集将类似于:

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

我已经尝试了几种不同的子查询方法,但总是出现错误 - 这非常令人沮丧。

这是架构:

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 default 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");

最佳答案

试试这个吧

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'

使用 GROUP_CONCAT() 方法

关于mysql - 聚合联接表导致 MySQL 5 上的 SQL SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6329156/

相关文章:

带有左外连接的php mysql

mysql转储: Can you change the name of the table you're inserting into?

php - Mysql 子查询失败,需要帮助 :)

python - Pandas 合并101

mysql - 在 MySQL 中查找表数据并将其替换为另一个表

sql - 从 SQL 注入(inject)生成的查询有多安全?

mysql - 如何将 10 GB 数据转储加载到表中

php - Codeigniter 在数据透视表上连接 2 个表

php - 通过 IP 显示国家标志

sql - ORA-00923 : FROM keyword not found where expected & ERROR: ORA-01756: quoted string not properly terminated