Bug #1675 select from ((select....) union all (select...)) group by....
| Submitted: | 27 Oct 2003 6:54 | Modified: | 27 Nov 2005 11:25 |
|---|---|---|---|
| Reporter: | Mike Nix | Email Updates: | |
| Status: | Closed | Impact on me: | |
| Category: | MySQL Server | Severity: | S4 (Feature request) |
| Version: | 4.1.0 | OS: | Linux (Linux) |
| Assigned to: | CPU Architecture: | Any |
[27 Nov 2005 11:25]
Valeriy Kravchuk
Thank you for a featurte request. You can do selects similar to what you wanted in MySQL 5.0.x: mysql> select count(*) from ((select 1 a from t1) union all (select 2 from t1)) t; +----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.18 sec) mysql> select version(); +-----------+ | version() | +-----------+ | 5.0.15-nt | +-----------+ 1 row in set (0.03 sec)
Portions of this website are copyright © 2001, 2002 The PHP Group
Page generated in 0.039 sec. using MySQL 8.4.7-u6-cloud
Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the
respective copyright holders.
It is not reviewed in advance
by Oracle and does not necessarily represent the opinion of
Oracle or any other party.
Description: I have a table of items which can be in one or two of many categories. The categories each item is in are stored in item.category1 and item.category2 To retrieve the total number of items in each category, I need to sum the count of items grouped by category - items are allowed to be counted twice. How to repeat: create table items (iid int, category1 char(10), category2 char(10)); mysql> (select count(*) '_items',category1 'category' from items group by category1) union all (select count(*),category2 from items group by category2); +--------+------------+ | _items | category | +--------+------------+ | 1 | boo1 | | 1 | booadu1 | | 1 | com1 | | 1 | NULL | | 1 | antboo1 | | 1 | com1 | +--------+------------+ 6 rows in set (0.00 sec) I need to select sum(_items),category from the above, grouped by category - a temp table would do it, but a single statement would be handy..... Suggested fix: as a workaround...... (this is ok because the NULL category above is caused by items in only one category, so we don't want to count it anyway) select if(c1._items,c1._items,0)+if(c2._items,c2._items,0) '_items', name 'category' from categories left join (select count(*) '_items',category1 from items group by category1) as c1 on categories.name=c1.category1 left join (select count(*) '_items',category2 from items group by category2) as c2 on categories.name=c2.category2 having _items>0; +--------+----------+ | _items | category | +--------+----------+ | 1 | antboo1 | | 1 | boo1 | | 1 | booadu1 | | 2 | com1 | +--------+----------+ 4 rows in set (0.02 sec)