我的桌子很少。 1.区域 2.餐厅 3.restaurant_itmes
区域
id | name
................
1 | NY
2 | Paris
3 | London
餐厅
id | name | region_id
.........................
1 | KFC | 1
2 | McDonals'| 1
3 | La res | 2
4 | Queen's | 3
restaurant_items
id | name | restaurant_id | pro_pic | featured_pic
...................................................
1 |Pizza |3 | null | defaut.jpg
2 |Pizza |4 | pizza.jpg | defaut.jpg
3 |Burger|1 | burger.jpg| burger.jpg
4 |Burger|2 | burger.jpg| burger.jpg
5 |Burger|3 | null | burger.jpg
6 |Burger|4 | null | default.jpg
7 |Donat |2 | null | default.jpg
8 |Fries |2 | null | default.jpg
我想生成一个查询以填充此表
region |Number of restaurants |total items | items_with_pro_pic | items_with_featured_pic
............................................................................................
NY | 2 | 4 | 2 | 2
Paris | 1 | 2 | 0 | 1
London | 1 | 2 | 1 | 0
我到目前为止所做的是
SELECT region.name, count(restaurant_items.id) as total_items, count(restaurant_items.pro_pic)
INNER JOIN restaurant on restaurant_items.restaurant_id = restaurant.id
INNER JOIN region on restaurant.region_id = region.id
GROUP BY region.name;
在这里我可以通过count(restaurant_items.pro_pic)获得items_with_pro_pic
但是我不能为items_with_featured_pic做到这一点,因为如果没有值,featured_pic不能为null
默认值为default.jpg。
所以我尝试了count(restaurant_items.featured_pic != 'defaut.jpg')
,但这对我不起作用。
由于餐厅不是restaurant_items表的一部分,如何获得餐厅数量?
如何使用MySQL实现这两个目标?
答案 0 :(得分:1)
用例何时
SELECT region.name, count(restaurant_items.id) as total_items, count(restaurant_items.pro_pic),
count(case when restaurant_items.featured_pic != 'defaut.jpg' then 1 end) as
items_with_featured_pic,
count(case when pro_pic is null then 1 end) as
items_with_pro_pic_null
INNER JOIN restaurant on restaurant_items.restaurant_id = restaurant.id
INNER JOIN region on restaurant.region_id = region.id
GROUP BY region.name
答案 1 :(得分:1)
您可以使用case
表达式而不是null
来生成default.jpg
,以便在count
函数中使用:
SELECT region.name,
COUNT(restaurant_items.id) as total_items,
COUNT(restaurant_items.pro_pic),
COUNT(CASE WHEN restaurant_items.featured_pic != 'default.jpg' THEN 1 END)
INNER JOIN restaurant ON restaurant_items.restaurant_id = restaurant.id
INNER JOIN region ON restaurant.region_id = region.id
GROUP BY region.name;
答案 2 :(得分:1)
您可以将COUNT
更改为SUM
并在IF语句上运行它:
SUM(IF(restaurant_items.featured_pic != 'default.jpg',1,0))
或者,也可以根据需要将其指定为COUNT
,但ELSE部分将需要为NULL而不是0,因为否则它仍将对其进行计数:
COUNT(IF(restaurant_items.featured_pic != 'default.jpg',1,NULL))
要计算餐厅数量,您可以简单地进行计数:
COUNT(DISTINCT restaurant.id)
一些小提示: