2012-09-26 83 views
3

我在mysql中查詢group concats記錄並給出具有冗餘標記的值。下面是查詢的輸出:mysql從字符串列表中獲得不同的標記

Problem Area->ACC-HO->ACC-HO->Credit Note (C/N)->Problem description ->Problem description 

但我想這個字符串的鮮明標記,如下

Problem Area->ACC-HO->Credit Note (C/N)->Problem description 

有沒有一種方法在sql SELECT查詢本身做到這一點?

編輯 這裏是schema and query 下面是我的查詢:

SELECT 
t2.transaction_id AS transaction_id, 
GROUP_CONCAT(
CONCAT(
t1.display_text, 
'->', 
    (CASE (NOT EXISTS (SELECT 1 FROM mst_node a WHERE a.parent_node_id = t1.node_id)) 
     WHEN 1 THEN t1.display_text ELSE 
     (SELECT b.display_text AS DISPLAY FROM mst_node b 
     WHERE parent_node_id = t2.node_id AND b.display_seq = t2.entered_value) 
    END) 
    ) 
    ORDER BY t2.logtime_stamp SEPARATOR '->' 
) AS display_text 
FROM 

mst_node t1 
    JOIN trn_user_log t2 
    ON t1.app_id = t2.app_id AND t1.node_id = t2.node_id  
WHERE (t1.app_id = 105) 
    AND t1.parent_node_id IS NOT NULL 
    AND t1.save_as_default IS NULL 
GROUP BY transaction_id, 
    mobile_no 
ORDER BY t2.transaction_id DESC, 
    t2.logtime_stamp, 
    t2.mobile_no 
+0

你知道你並不需要所有那些醜陋的反引號? –

+0

:-)是的,我知道... mysql客戶端.. – DarkKnightFan

回答

0

我終於能夠通過使用兩者的UNION選擇查詢,然後做一個GROUP_CONCAT(DISTINCT column ORDER BY another_column)來解決我的問題。

下面是我使用的查詢:

SELECT 
transaction_id, 
GROUP_CONCAT(DISTINCT display_text ORDER BY logtime_stamp SEPARATOR '->') AS display_text 
FROM 
(SELECT 
    t2.transaction_id AS transaction_id, 
    t2.logtime_stamp, 
    t1.display_text AS display_text 
    FROM mst_node t1 
    JOIN trn_user_log t2 ON t1.app_id = t2.app_id 
    AND t1.node_id = t2.node_id 
    WHERE (t1.app_id = 105) 
    AND t1.parent_node_id IS NOT NULL 
    AND t1.save_as_default IS NULL 
    UNION 
SELECT t2.transaction_id AS transaction_id,t2.logtime_stamp, 
    CASE(NOT EXISTS (SELECT 1 FROM mst_node a WHERE a.parent_node_id = t1.node_id)) 
    WHEN 1 THEN NULL 
    ELSE (SELECT b.display_text AS display_text FROM mst_node b WHERE parent_node_id = t2.node_id AND b.display_seq = t2.entered_value) 
    END AS display_text 
FROM mst_node t1 JOIN trn_user_log t2 
     ON t1.app_id = t2.app_id AND t1.node_id = t2.node_id  
    WHERE (t1.app_id = 105) 
    AND t1.parent_node_id IS NOT NULL 
    AND t1.save_as_default IS NULL 
    ORDER BY transaction_id DESC,logtime_stamp 
) AS T 
    GROUP BY transaction_id 
    ORDER BY transaction_id DESC,logtime_stamp 
5

在你GROUP CONCAT添加DISTINCT所以它只會串連唯一值。

SELECT GROUP_CONCAT(DISTINCT colName),.... 
FROM ... 
WHERE ... 
GROUP BY ... 

SQLFiddle Demo

+0

你能提供數據嗎? [見SQLFiddle示例](http://sqlfiddle.com/#!2/f8fa6/3) –

+0

是的..試圖提供架構...其相當龐大涉及3個表... – DarkKnightFan

+0

我已經添加架構和查詢作爲鏈接到sqlFiddle。請檢查現在... – DarkKnightFan

0

您的分組子句中,你可以通過這個字符串列另一個group by添加到組的爲好。

SELECT GROUP_CONCAT(myStringColumn),.... 
FROM ... 
WHERE ... 
GROUP BY myOtherColumn,myStringColumn 
+0

,如果在myOtherColumn上有'myStringColumn'的另一個值,它將創建另一行。嘗試一下。 –

+1

[看這個](http://sqlfiddle.com/#!2/59bdc/1):D –

+0

:(錯誤的猜測,我會在幾分鐘內刪除這個答案。 – DhruvPathak