SQL如何将这三个视图合并为一个?

时间:2013-10-19 18:42:32

标签: mysql sql

如何加入以下两个视图?我自己尝试过,但他们总是打破,并显示重复的数据。我能想到的唯一工作是创建两个视图,然后是第三个视图来加入两个视图。问题是,对于我的应用程序,我将有大约10个视图,这些视图效率不高,设计不正确。

查看1

SELECT e.id, e.name, GROUP_CONCAT(email SEPARATOR ', ') AS array_emails
FROM entity AS e
LEFT JOIN emails ON e.id=emails.entity_id
GROUP BY id; 

查看2

SELECT e.id, e.name, GROUP_CONCAT(web_site SEPARATOR ', ') AS array_web_sites
FROM entity AS e
LEFT JOIN web_sites ON e.id=web_sites.entity_id
GROUP BY id 

查看3 (此视图将视图1和2连接在一起)

SELECT e.id, e.name, view_web_sites.array_web_sites, view_emails.array_emails
FROM entity AS e
LEFT JOIN view_web_sites ON e.id=view_web_sites.id
LEFT JOIN view_emails ON e.id=view_emails.id
GROUP BY id

这是我的原始视图,它无法正常工作。值会重复。

原创 - 视图破碎     选择e.id,e.name,GROUP_CONCAT(电子邮件SEPARATOR',')AS电子邮件,     GROUP_CONCAT(web_site SEPARATOR',')AS web_sites     来自实体AS e     LEFT JOIN电子邮件ON e.id = emails.entity_id     LEFT JOIN web_sites ON e.id = web_sites.entity_id     GROUP BY id;

编辑: 我已经在select语句中探索了distinct参数,该参数非常有效。但是在一个表中我有一个二进制列,并且distinct参数“擦除”该值,使列无用。关于此事的任何建议?

编辑#2(FIX): 我设法为可能遇到类似问题的任何人解决了这个问题。

SELECT entity.id, entity.name,
(SELECT GROUP_CONCAT(emails.email) FROM emails WHERE entity.id=emails.entity_id) AS emails_array,
(SELECT GROUP_CONCAT(web_sites.web_site) FROM web_sites WHERE
entity.id=web_sites.entity_id) AS websites_array
FROM entity
ORDER BY id 

1 个答案:

答案 0 :(得分:0)

SELECT e.id, 
       e.name, 
       GROUP_CONCAT(DISTINCT m.email SEPARATOR ', ') AS array_emails,
       GROUP_CONCAT(DISTINCT w.web_site SEPARATOR ', ') AS array_web_sites
FROM entity AS e
  LEFT JOIN emails AS m ON e.id = m.entity_id
  LEFT JOIN web_sites AS w ON e.id = w.entity_id
GROUP by e.id ; 

如果您使用这些视图,则不需要上一个GROUP BY id

SELECT e.id, 
       e.name, 
       m.array_emails,
       w.array_web_sites
FROM entity AS e
  LEFT JOIN view_emails AS m ON e.id = m.entity_id
  LEFT JOIN view_web_sites AS w ON e.id = w.entity_id ; 

如果您不想要嵌套视图,可以使用一个查询编写它 - 并通过删除派生表中的连接来简化它:

SELECT e.id, 
       e.name, 
       m.array_emails,
       w.array_web_sites
FROM entity AS e
  LEFT JOIN 
    ( SELECT entity_id, 
             GROUP_CONCAT(email SEPARATOR ', ') AS array_emails
      FROM emails
      GROUP BY entity_id 
    ) AS m ON e.id = m.entity_id
  LEFT JOIN 
    ( SELECT entity_id, 
             GROUP_CONCAT(web_site SEPARATOR ', ') AS array_web_sites
      FROM web_sites
      GROUP BY entity_id 
    ) AS w ON e.id = w.entity_id ;