Join and group concat mysql查询未按预期工作

Join and group concat mysql查询未按预期工作,mysql,Mysql,我有3个主表,如下所示: Table POSTS pid int auto_increment parentID int, other data fields... Table TAGS id int auto_increment pid int (to join with POSTS) tags char (stores only one tag) 所以,如果一篇文章有两个标签,那么标签表中会有两个条目,每个标签对应一个条目 Table CT (customer tags) id int

我有3个主表,如下所示:

Table POSTS
pid int auto_increment
parentID int,
other data fields...

Table TAGS
id int auto_increment
pid int (to join with POSTS)
tags char (stores only one tag)
所以,如果一篇文章有两个标签,那么标签表中会有两个条目,每个标签对应一个条目

Table CT (customer tags)
id int auto_increment
tag varchar (one tag stored)
customerID (to join with main user table)
我没有提到主用户表的结构,因为这与问题无关

以下是我试图做的:

选择一个帖子,将其标签分组(2,3,4个,数量为其数量的2,3,4个) 但只有那些在CT表中也有匹配标签的帖子才会被选中

不同的用户分配了不同的标签。 因此,如果用户有这两个标签,“美丽”和“时尚”, 然后,只会选择那些至少有一个标签的帖子

最后的结果应该是将连接到柱子上的标签分组。 例如,帖子可以有3个标签,“美丽”、“风格”和“服饰”。 这些必须作为结果返回

下面是我正在使用的SQL,不起作用

group_concat未对连接到POST的标记进行分组。 相反,它为所选用户对CT表中的所有标记进行合并

此外,也不会选择所有匹配的帖子。 我不知道为什么

SQL:


您需要使用group by,不要使用distinct with group_concat添加一些示例数据和预期输出。请参阅
select 
distinct( p.pid ), p.parentID, p.title
c.stat, c.username, 
group_concat( t.tag ) as tags 
from 
POSTS as p, 
USERS as c, 
TAGS as t, 
CT as ct 
where 
 p.parentID='0' and 
t.pid=p.pid and 
ct.tag=t.tag and 
ct.userid='$userid' 
order by p.sdate desc limit 30
select 
p.pid, p.parentID, p.title
c.stat, c.username, 
group_concat( t.tag ) as tags 
from 
POSTS as p, 
USERS as c, 
TAGS as t, 
CT as ct 
where 
p.parentID='0' and 
t.pid=p.pid and 
ct.tag=t.tag and 
ct.userid='$userid' 
group by t.pid
order by p.sdate desc limit 30