2011-02-16 129 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