按类型限制SQL结果(列值)

时间:2011-02-16 17:53:32

标签: sql limit

我有一张DailyMeal表:

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

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

单一查询是否可行?没有存储过程。

编辑:是联盟。谢谢所有海报。

5 个答案:

答案 0 :(得分: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)

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')

答案 2 :(得分:1)

怎么样

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

答案 3 :(得分:1)

我认为你可以使用UNION实现这一目标 - 将所有具有蔬菜类型的人联合起来,以及限制1个水果的单独查询。

答案 4 :(得分:1)

试试这个:

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