0

我有一个站点和一个相关的 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 表中,关于属物的信息存储在“belonging”列(值: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

我会问你是否可以用一个查询来做到这一点......

4

1 回答 1

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) 
  )
于 2013-04-27T09:32:45.703 回答