请查看此fiddle
是否可以将这四个不同的查询合并为一个语句?
SELECT DISTINCT(name) from `product` order by name;
SELECT DISTINCT (category) from `product` order by category;
SELECT DISTINCT (price) from `product` order by price;
SELECT DISTINCT (year) from `product` order by year;
我希望从每列获得不同的行,并以JSON格式返回选择框选项的结果,但我不知道如何在不使用四个独立的select语句的情况下返回如下结果:
NAME
A
C
D
E
G
CATEGORY
Brainteaser
Doll
Outdoor
PRICE
20
22
25
30
34
YEAR
2008
2009
2010
表:
CREATE TABLE产品
(ID
int,name
varchar(1),category
varchar(11),price
int,year
int)
;
INSERT INTO product
(`ID`, `name`, `category`, `price`,`year`)
VALUES
(1, 'A', 'Outdoor', 25,2010),
(2, 'A', 'Doll', 34,2009),
(3, 'C', 'Doll', 25,2008),
(4, 'D', 'Outdoor', 20,2010),
(5, 'E', 'Brainteaser', 22,2010),
(6, 'E', 'Brainteaser', 22,2009),
(7, 'G', 'Brainteaser', 30,2009),
(8, 'G', 'Brainteaser', 30,2009)
;
答案 0 :(得分:1)
可能你可以尝试这样的事情:
SELECT DISTINCT(name) FIELDVALUE, 'NAME' FIELDNAME from `product`
UNION
SELECT DISTINCT (category) FIELDVALUE, 'CATEGORY' FIELDNAME from `product`
UNION
SELECT DISTINCT (price) FIELDVALUE, 'PRICE' FIELDNAME from `product`
UNION
SELECT DISTINCT (year) FIELDVALUE, 'YEAR' FIELDNAME from `product` ;
它输出为:
FIELDVALUE FIELDNAME
A NAME
C NAME
D NAME
E NAME
G NAME
Outdoor CATEGORY
Doll CATEGORY
Brainteaser CATEGORY
25 PRICE
34 PRICE
20 PRICE
22 PRICE
30 PRICE
2010 YEAR
2009 YEAR
2008 YEAR