MySQL JOIN使用三个表

时间:2013-11-29 18:09:31

标签: mysql left-join

我需要查询从三个表中获取值。所以,我正在使用它:

SELECT 
menussite.MSS_D1sMenu, menussite.MSS_CdiVertical, 
verticais.VER_D1sVertical, 
GROUP_CONCAT(submenussite.SSS_D1sSubMenuSite) 

FROM menussite 
LEFT JOIN verticais ON verticais.VER_CdiVertical = menussite.MSS_CdiVertical 
LEFT JOIN submenussite ON submenussite.SSS_CdiMenuSite = menussite.MSS_CdiMenuSite 
ORDER BY menussite.MSS_CdiMenuSite ASC

问题是某些单元格为空,查询只显示与查询完全匹配的行。我需要做什么来查询而不忽略其他结果?

更新

这是一个SQL小提琴:http://sqlfiddle.com/#!2/11eabb/2

2 个答案:

答案 0 :(得分:1)

尝试或修改此查询

SELECT 
m.menu as a, m.vertical as b, v.vertical as c, s.submenu as d
from menu m, vertical v, submenu s where m.id=v.id and m.id=s.id
ORDER BY m.menu ASC

结果

http://sqlfiddle.com/#!2/11eabb/5/0

A     B  C  D            e  
item  1  1  vertical 1   submenu 1
item  2  0  vertical 2   submenu 1

答案 1 :(得分:0)

您缺少GROUP BY menu.menu

SELECT menu.menu,
       menu.vertical,
       vertical.vertical,
       GROUP_CONCAT(submenu.submenu)    
FROM menu
LEFT JOIN vertical ON vertical.id = menu.vertical     
LEFT JOIN submenu ON submenu.menu = menu.id 
GROUP BY menu.menu
ORDER BY menu.menu ASC

sqlfiddle demo

这将为您提供没有子菜单的值:

MENU    VERTICAL    GROUP_CONCAT(SUBMENU.SUBMENU)
item 1  1           submenu 1,submenu 1
item 2  0           (null)
item 3  2           (null)
item 4  0           (null)