2011-02-16 122 views
2

我有一个表DailyMeal:限制SQL结果

Name  | Type 
------------------------ 
orange | fruit 
carrot | vegetable 
apple | fruit 
potato | vegetable 
eggplant | vegetable 
cucumber | vegetable 
lemon | fruit 

我的查询应该返回所有的蔬菜,有且仅有一个水果,无所谓哪一个。

单查询可能吗?没有存储过程。

编辑:是的,它是联盟。感谢所有海报。

+0

你应该总是陈述DBMS,如果可能的版本。 – RichardTheKiwi 2011-02-16 18:01:44

回答

4
select * from daily_meal where type = 'fruit' limit 1 
union 
select * from daily_meal where type = 'vegetable' 

例如

mysql> desc daily_meal; 
+-------+--------------+------+-----+---------+-------+ 
| Field | Type   | Null | Key | Default | Extra | 
+-------+--------------+------+-----+---------+-------+ 
| name | varchar(100) | YES |  | NULL |  | 
| type | varchar(100) | YES |  | NULL |  | 
+-------+--------------+------+-----+---------+-------+ 
2 rows in set (0.00 sec) 

mysql> select * from daily_meal; 
+----------+-----------+ 
| name  | type  | 
+----------+-----------+ 
| apple | fruit  | 
| potato | vegetable | 
| eggplant | vegetable | 
| cucumber | vegetable | 
| lemon | fruit  | 
| orange | fruit  | 
| carrot | vegetable | 
+----------+-----------+ 
7 rows in set (0.00 sec) 

mysql> select * from daily_meal where type = 'fruit' limit 1 
    -> union 
    -> select * from daily_meal where type = 'vegetable'; 
+----------+-----------+ 
| name  | type  | 
+----------+-----------+ 
| apple | fruit  | 
| potato | vegetable | 
| eggplant | vegetable | 
| cucumber | vegetable | 
| carrot | vegetable | 
+----------+-----------+ 
5 rows in set (0.00 sec) 
+1

纠正我,如果我错了,但你写它的方式返回限制1对整个UNION编辑集 – RichardTheKiwi 2011-02-16 18:00:42

1
select * from DailyMeal where Type = 'vegetable' or Name = 'orange' 

select * from DailyMeal where Type = 'vegetable' or Name in (select top 1 Name from DailyMeal where Type = 'fruit') 
+0

增加了第二个使用子查询的例子。 – Brandon 2011-02-16 17:58:02

1

我如何

SELECT * FROM DailyMeal WHERE Type = 'vegetable' 
UNION Select TOP 1 * FROM DailyMeal WHERE Type = 'fruit' 
1

觉得你能做到这一点USI一个联盟 - 将所有那些拥有一种蔬菜的人联合在一起,另一个问题是限制一个水果。

1

试试这个:

SELECT * 
    FROM DailyMeal 
WHERE type = 'vegetable' 
UNION ALL 
SELECT * 
    FROM (
       SELECT * 
       FROM DailyMeal 
      WHERE type = 'fruit' 
      LIMIT 1 
      ) a