简体   繁体   中英

MySQL Group by only if condition

I'm having hard time trying to find if I can do this. So, from one table, I want to use GROUP BY only if the w.type is 'object' the other object don't have to be grouped.

SELECT COUNT(*) as number, w.name, w.type
FROM storage AS s
LEFT JOIN weapon AS w ON w.id=s.weapon_id
WHERE s.owner_id = 'ID'
GROUP BY s.name
ORDER BY w.type

As you can see, this query group by everything.

I tried with UNION but it seems compromised because the double query is on the same table. And I looked for Case, but I'm not sure how to use it.

Thanks for reading !

Edit : This is for displaying inventory in game. Each weapons buckler are unique but you can have few different weapons with the same w.name. Objects don't have this constraint, I need them group by and show to the player the number of the same item.

Player will see this :

Player Inventory

  • Weapon

Diamond Sword, Iron Sword, Iron Sword

  • Object

Apple x2, Pear x3, Egg x1

You mention you've tried a UNION, but unless I'm just tired and missing something, does this not work?

SELECT COUNT(*) as number, w.name, w.type 
FROM storage AS s 
LEFT JOIN weapon AS w ON w.id=s.weapon_id 
WHERE s.owner_id = 'ID' AND w.type = 'Object' 
GROUP BY s.name 
UNION
SELECT 1 as number, w.name, w.type 
FROM storage AS s 
LEFT JOIN weapon AS w ON w.id=s.weapon_id 
WHERE s.owner_id = 'ID' AND w.type != 'Object' 
GROUP BY w.id
ORDER BY w.type

In the second select, the group by would be a unique identifier - I'm assuming name and type would be sufficient, but I'm shooting blind without seeing data

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