开发者

Limit SQL result by type (column value)

I have a table DailyMeal:

Name     | Type
------------------------
orange   | fruit
carrot   | vegetable
apple    | fruit
potato   | vegetable
eggplant | vegetable
cu开发者_StackOverflowcumber | vegetable
lemon    | fruit

My query should return all vegetables and one and only one fruit, doesn't matter which one.

Is it possible with single query? No stored procedure.

Edit: Yes union it is. Thanks all posters.


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

example

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)


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

or

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


I think you could achieve this using a UNION - to join together all those with a type of vegetables, and a separate query that limts 1 of fruit.


Try this:

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


How about

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜