简体   繁体   中英

Combine two rows in select query having same id's

I have this query

SELECT 
`sys_forms`.`FormID`,
`sys_forms`.`FormName`,
`sys_forms`.`FormCIPath`,
`sys_forms_in_groups`.`IsMenuLink`,
`sys_forms_in_groups`.`GroupID`

FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups` 
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 1
UNION
SELECT 
`sys_forms`.`FormID`,
`sys_forms`.`FormName`,
`sys_forms`.`FormCIPath`,
`sys_forms_in_groups`.`IsMenuLink`,
`sys_forms_in_groups`.`GroupID`

FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups` 
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 2

it is returning me this below data.

在此处输入图片说明

As you can see, there are two identical FormID .

What i want that if the id's are same then rows should be merged but GroupID is different for both identical FormID's.

So i want them to join in CSV format so that the result would be

FormID FormName        -  -   GroupID
-------------------------------------------------
48     FormsIn Groups  -  -    1,2          

Your first query can just be written as:

SELECT sf.`FormID`, sf.`FormName`, sf.`FormCIPath`, sfig.`IsMenuLink`, sfig.`GroupID`
FROM `sys_forms` sf INNER JOIN
     `sys_forms_in_groups` sfig
     ON sfig.`FormID` = sf.`FormID`
WHERE `GroupID` IN (1, 2);

Note the use of table aliases and the single where clause with in .

To get what you want, use group by and include only the columns you want:

SELECT sf.`FormID`, sf.`FormName`, 
       group_concat(sfig.`GroupID`) as groupids
FROM `sys_forms` sf INNER JOIN
     `sys_forms_in_groups` sfig
     ON sfig.`FormID` = sf.`FormID`
WHERE `GroupID` IN (1, 2)
GROUP BY sf.`FormID`, sf.`FormName`, sf.`FormCIPath`, sfig.`IsMenuLink`;

The specified result can be returned with a query like this:

SELECT f.FormID
     , f.FormName
     , f.FormCIPath
     , MAX(g.IsMenuLink) AS IsMenuLink
     , GROUP_CONCAT(DISTINCT g.GroupID ORDER BY g.GroupID) AS GroupIDs
  FROM `sys_forms` f 
  JOIN `sys_forms_in_groups` g
    ON g.FormID = f.FormID
   AND g.GroupID IN (1,2)
 GROUP BY f.formID

The GROUP_CONCAT aggregate will combine multiple values into a comma separated list. (A different delimiter can be specified, the default is a comma.)

We use the MAX aggregate around the IsMenuLink column so we get a non-NULL value in place of NULL.

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