MySQL - 具有相同表和另一个表的多连接

时间:2013-04-27 08:50:28

标签: mysql join

我有一个网站和一个相对CMS,其中启用的用户可以查看和编辑网站页面内容和信息。每个页面都与一个菜单语音相关联,用户可以通过该菜单打开和查看该页面。页面和菜单分别存储在pm_sections和pm_menu表中。当CMS用户想要插入新页面时,他必须指定相关菜单语音的所有权。有三个属性级别:

-> menu group (1)
   -> main menu voice (2), inside a menu group
      -> secondary menu voice (3), inside a main menu voice

在pm_menu表中,关于所有物的信息存储在“所属”栏(值:1,2或3)和“menu_id”栏(菜单语音所属ID)中。还有另一个表pm_menu_groups,其中包含主菜单组。

我的问题如下:我必须加入部分和菜单表,以便列出CMS页面编辑页面中的信息。我试过用UNION子句来做这件事:

SELECT s_id, section_name, menu_name, seo_title, last_edit
FROM 
((SELECT s.id AS s_id, s.name AS section_name, s.content AS content, m.belonging AS belonging, m.menu_id AS menu_id, n.name AS menu_name, s.seo_title AS seo_title, s.added_by AS author, s.modify_date AS last_edit FROM pm_sections s, pm_menu m, pm_menu n
WHERE m.section_id = s.id
AND m.link IS NULL
AND m.menu_id = n.id
AND m.belonging = 3)

UNION

(SELECT s.id AS s_id, s.name AS section_name, s.content AS content, m.belonging AS belonging, m.menu_id AS menu_id, n.name AS menu_name, s.seo_title AS seo_title, s.added_by AS author, s.modify_date AS last_edit
FROM pm_sections s, pm_menu m, pm_menu n
WHERE m.section_id = s.id
AND m.link IS NULL
AND m.menu_id = n.id
AND m.belonging = 2)

UNION

(SELECT s.id AS s_id, s.name AS section_name, s.content AS content, m.belonging AS belonging, m.menu_id AS menu_id, g.name AS menu_name, s.seo_title AS seo_title, s.added_by AS author, s.modify_date AS last_edit
FROM pm_sections s, pm_menu m, pm_menu_groups g
WHERE m.section_id = s.id
AND m.link IS NULL
AND m.menu_id = g.id
AND m.belonging = 1))

AS belongings_table
ORDER BY section_name

我会问你是否可以通过一个查询来完成...

1 个答案:

答案 0 :(得分:0)

查看外部查询,不使用以下字段

s.added_by AS author, 
s.content AS content, 
m.belonging AS belonging, 
m.menu_id AS menu_id, 

所以我猜他们不需要被包括在内

<强>差异

如果我正确读取其他三个查询,唯一的区别在于where子句

AND m.menu_id = n.id
AND m.belonging = 3

AND m.menu_id = n.id
AND m.belonging = 2

AND m.menu_id = g.id
AND m.belonging = 1

可以简化为

AND m.menu_id = n.id
AND m.belonging in (2, 3)

AND m.menu_id = g.id
AND m.belonging = 1

<强>最后 并制作成正确的sql(除非我有一两个类型)

SELECT 
  s.id AS s_id, 
  s.name AS section_name, 
  n.name AS menu_name, 
  s.seo_title AS seo_title, 
  s.modify_date AS last_edit
FROM 
  pm_sections s, 
  pm_menu m, 
  pm_menu n, 
  pm_menu_groups g
WHERE 
  m.section_id = s.id AND 
  m.link IS NULL AND 
  ( 
    ( m.menu_id = n.id AND m.belonging In (2,3) ) or
    ( m.menu_id = g.id AND m.belonging = 1) 
  )