简体   繁体   中英

GROUP_CONCAT && left outer join on 1 table?

I've got 1 table with Menu labels in it.I need with a query to get Parent label and UnderMenu label.when i execute this:

  SELECT es.Label MenuLabel, m.Label UnderLabel 
  FROM books_menu es
  LEFT JOIN books_menu m ON es.ID = m.MenuParentID 
  WHERE es.ParentID =1 
  AND m.Type='under'
  AND es.Type='main' 
  LIMIT 0 , 30

everything is OK but MenuLabel show on every record.Something like this:

  MenuLabel    UnderLabel
  Home         1
  Home         2
  Home         3
  Contacts     4

When i execute :

  SELECT es.Label MenuLabel, GROUP_CONCAT(m.Label) AS UnderLabel 
  FROM books_menu es
  LEFT JOIN books_menu m ON es.ID = m.MenuParentID 
  WHERE es.ParentID =1 
  AND m.Type='under'
  AND es.Type='main' 
  LIMIT 0 , 30

i get:

      MenuLabel    UnderLabel
       Home         1,2,3,4

How can i get this:

   MenuLabel    UnderLabel
   Home         1,2,3
   Contacts     4

Thank you:)

You need to have GROUP BY clause:

SELECT es.Label MenuLabel, GROUP_CONCAT(m.Label) AS UnderLabel 
FROM books_menu es
LEFT JOIN books_menu m ON es.ID = m.MenuParentID 
WHERE es.ParentID =1 
      AND m.Type='under'
      AND es.Type='main' 
GROUP BY MenuLabel    
LIMIT 0 , 30;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM