我有下表,描述了一些植物
p_id p_type p_name p_size p_tasty
1 veggie potato 1 0
2 veggie carrot 2 0
3 veggie cabbage 3 0
4 fruit strawberry 1 1
5 fruit apple 2 0
6 fruit watermelon 3 0
如果我想获得每种类型的最大工厂,查询将是这样的:
SELECT a.p_id,a.p_type, a.p_name,a.p_size,a.p_tasty
FROM test.plants a
INNER JOIN (
SELECT b.p_type, MAX(b.p_size) p_size
FROM test.plants b
GROUP BY b.p_type
) b ON a.p_type = b.p_type AND a.p_size = b.p_size
并会给我这个:
p_id p_type p_name p_size p_tasty
3 veggie cabbage 3 0
6 fruit watermelon 3 0
但我怎样才能获得各种最大或最美味的植物?
即 选择p_tasty值为1的工厂,如果没有此类工厂,请选择最大工厂。
我想我可以使用case when exists then ...
子句,但也许有更简单的方法可以做到这一点?
答案 0 :(得分:1)
LEFT JOIN
您对美味植物的查询,如果没有美味的植物,请使用最大的默认植物。
SELECT IFNULL(c.p_id, a.p_id) AS p_id, a.p_type, IFNULL(c.p_name, a.p_name) AS p_name, IFNULL(c.p_size, a.p_size) AS p_size, IFNULL(c.p_tasty, a.p_tasty) AS p_tasty
FROM test.plants a
INNER JOIN (
SELECT b.p_type, MAX(b.p_size) p_size
FROM test.plants b
GROUP BY b.p_type
) b ON a.p_type = b.p_type AND a.p_size = b.p_size
LEFT JOIN test.plants c ON a.p_type = c.p_type AND c.tasty = 1
答案 1 :(得分:0)
或者根据需要在row_number()顺序上使用partition by:
if($form->isSubmitted() && $form->has('get_away_from_form')){
if($form->get('get_away_from_form')->isClicked() == 1){
$isClicked = 'It works as expected: $form->get(get_away_from_form)->isClicked() = '.$form->get('get_away_from_form')->isClicked();
} else {
$isClicked = 'It DOESN\'T work as expected: $form->get(get_away_from_form)->isClicked() = '.$form->get('get_away_from_form')->isClicked();
}
}