连接表时显示多个值

时间:2014-01-13 13:48:18

标签: mysql

您好我正在尝试以下查询 我有四张表post_messages post_message_userslink_detailstags post_messages与link_detailstags有1:N关系  表 我正在编写以下查询来从所有表中获取相关数据。 但问题是它多次显示相同的值。

           SELECT
             p_m.*,
             p_m_u.*,
             GROUP_CONCAT( tags.tag SEPARATOR ';') 
             AS 'MESSAGE_TAGS', 
             GROUP_CONCAT( linkdtl.link_id SEPARATOR ';') 
             AS `LINK_ID`, 
             GROUP_CONCAT( linkdtl.link SEPARATOR ';') 
             AS 'LINK', 
             GROUP_CONCAT( linkdtl.link_title SEPARATOR ';') 
             AS 'LINK_TITLE' 
             FROM post_message_users AS p_m_u 
             LEFT JOIN post_messages AS p_m 
             ON p_m.messageid = p_m_u.messageid 
             LEFT JOIN tags 
             ON p_m.messageid=tags.message_id 
             LEFT JOIN link_details AS linkdtl
             ON p_m_u.messageid=linkdtl.message_id

             GROUP BY p_m_u.messageid,p_m_u.received_by,tags.message_id 
             ORDER BY p_m_u.adddate DESC 

如何解决此问题。

1 个答案:

答案 0 :(得分:0)

尝试在DISTINCT子句中使用GROUP_CONCAT

GROUP_CONCAT( DISTINCT tags.tag SEPARATOR ';') 


SELECT 
  p_m.*,
  p_m_u.*,
  GROUP_CONCAT(DISTINCT tags.tag SEPARATOR ';') AS 'MESSAGE_TAGS',
  GROUP_CONCAT(DISTINCT linkdtl.link_id SEPARATOR ';') AS `LINK_ID`,
  GROUP_CONCAT(DISTINCT linkdtl.link SEPARATOR ';') AS 'LINK',
  GROUP_CONCAT(DISTINCT linkdtl.link_title SEPARATOR ';') AS 'LINK_TITLE' ....