2015-10-14 92 views
0

我有兩個表:SQL查詢中使用GROUP_CONCAT()函數

1.Activity-- which stores all the activities from a user 
2.User-- which stores all the registered users 

我想獲取所有的帖子和喜歡的所有職位在一個查詢。一排是帖子或類似的由類型欄的值決定。

表名稱 - 活動

| actId | parentId | type  | postedby | 
--------------------------------------------------- 
| 100 | NULL  | post  | 100   | 
| 200 | 100  | like  | 200   | 
| 300 | 100  | like  | 300   | 
| 400 | 100  | like  | 400   | 
| 500 | NULL  | post  | 100   | 
| 600 | 500  | like  | 600   | 

表名稱 - 用戶

| userId | name | 
------------------- 
| 100  | Amit | 
| 200  | Alok | 
| 300  | Arjun | 
| 400  | Arpeet | 
| 600  | Amaan | 

輸出應該

| actId | name | LikedBy   | 
------------------------------------------ 
| 100 | Amit | Alok, Arjun, Arpeet| 
| 500 | Amit | Amaan    | 

注意 - 我不希望使用FOR XML PATH來實現此目的,因爲它在我正在使用的SQLite中不受支持。

我查詢的嘗試是

SELECT a.id, u.name, 
(select group_concat(u.name) from activity a, user u where a.id = u.id and a.type = 'like' 
group by a.parent) as likedby 
FROM activity a, user u 
WHERE a.id = u.id and a.type = 'post' 

我得到的結果是

| Id | name | LikedBy   | 
--------------------------------------- 
| 100 | Amit | Alok, Arjun, Arpeet| 

你可以看到在另一排從結果失蹤。

+2

您需要哪種DBMS解決方案? – Jens

+0

@Jens,我需要SQLite。但它可能不會很大,因爲查詢將幾乎相同。 –

+0

這是不正確的,GROUP_CONCAT()是一個mysql相關的函數,在SQL Server中它是一個遞歸的CTE(例如)。 – Pred

回答

1

試試這個:

select t.id4id Id, n1.Name Name, group_concat(n2.name) Groups 
from (select t1.actid id4id, t1.postedby id4name, t2.postedby id4groups 
     from Activity t1 join Activity t2 on t1.actid = t2.parentid) t join "user" n1 on t.id4name = n1.userid join "User" n2 on t.id4groups = n2.userid 
group by id4id 

注:1。我認爲一個帖子將永遠在父母

+0

非常感謝您的回覆。這似乎很難理解。但我仍然會按照我的要求使用它,因爲它對我來說工作得很好。 –

0

空值你並不需要爲這個子查詢。你只需要以獲取值的原始名字和喜歡的名稱中的兩個連接:

select a.parentid, u.name, group_concat(ul.name separator ', ') as likedby 
from activity a join 
    user ul 
    on a.postedby = ul.userid join 
    user u 
    on a.parentid = u.userid 
where a.type = 'like'; 

組由a.parentid,u.name;