[英]Join and group concat mysql query not working as expected
我有 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)
因此,如果 POST 有 2 個 TAGS,則 TAGS 表中將生成 2 個條目,每個 TAG 一個。
Table CT (customer tags)
id int auto_increment
tag varchar (one tag stored)
customerID (to join with main user table)
我沒有提到主用戶表的結構,因為這與問題無關。
這是我想要做的:
選擇一個 POST,group_concat 它的標簽(2,3,4 和它一樣多)但只選擇那些在 CT 表中也有匹配標簽的 POSTS
不同的用戶分配有不同的標簽。 因此,如果用戶有這 2 個標簽,“美女”和“時尚”,那么只會選擇那些也至少具有這些標簽之一的帖子。
最終結果應該是連接到 POSTS 的 group_concat 標簽。 例如,帖子可以有 3 個標簽,“美女”、“風格”和“連衣裙”。 這些必須在結果中返回。
下面是我正在使用的 SQL,不起作用,
group_concat 沒有對連接到 POST 的標簽進行分組。 相反,它為所選用戶連接 CT 表中的所有標簽。
此外,所有匹配的帖子也沒有被選中。 我不知道為什么...
查詢語句:
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
您需要使用 group by,不要將 distinct 與 group_concat 一起使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.