Join and group concat mysql query not working as expected

Sumit Kumar :

I have 3 main tables, like this:

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)

So, if a POST has 2 TAGS, then 2 entries will be made in TAGS table, one for each TAG.

Table CT (customer tags)
id int auto_increment
tag varchar (one tag stored)
customerID (to join with main user table)

I am not mentioning the structure of main user table, cause that is not relevant to question.

Here is what I am trying to do:

Select a POST, group_concat its tags (2,3, 4 as many as it has) but only those POSTS are selected which also have a matching tag in CT table

Different users have different tags assigned. So if a user has these 2 tags, "beauty" and "fashion", then only those posts will be selected which also have at least one of those tags.

Final result should group_concat tags which are connected to the POSTS. For example, the post can have 3 tags, "beauty" and "style" and "dress". These must be returned in result.

Below is the SQL I am using, does not works,

The group_concat is not grouping the tags which are connected to the POST. Instead its doing a concat of all the tags in the CT table for the selected user.

Additionally, all the matching posts are not getting selected either. I don't know why...

SQL:

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
Tushar :
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

You need to use group by, don't use distinct with group_concat

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31831&siteId=1