COALESCE的用法

时间:2016-08-15 11:15:49

标签: mysql coalesce

我有一个查询使用Conversion failed when converting the varchar value '0.01' to data type bit.来计算2列的组合:

COALESCE()

结果很有用。样本结果:

SELECT method, main_ingredient, COUNT(*) AS cnt FROM  `recipes` 
GROUP BY COALESCE( method, main_ingredient ) 

但是,如何获得method main_ingredient cnt ================================ 1 4 10 2 1 6 3 6 3 4 6 5 5 2 4 6 8 2 等于0?

的结果

更新预期输出:

COUNT(*)

更新添加了method main_ingredient cnt ================================ 1 2 0 1 3 0 1 5 0 1 6 0 2 2 0 2 3 0 . . . . etc tbl_methods

tbl_main_ingredients的架构:

tbl_methods

id method_name ================= 1 Method 1 2 Method 2 . . . 6 Method 6 的架构:

tbl_main_ingredients

两个id ingredient_name ====================== 1 Ingredient 1 2 Ingredient 2 . . . 8 Ingredient 8 都是其表的主键,自动递增。

3 个答案:

答案 0 :(得分:1)

首先,您需要在if ($request->ajax()) { if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { // Authentication passed... return 'success'; } else { return 'Invalid username/password'; } } CROSS JOIN表之间设置tbl_methods,以获得所有可能的方法和成分组合。

稍后在上面的交叉联接表和tbl_main_ingredients表格之间进行左联接,匹配reipesmethod

因此,您将获得main_ingredientmethod的所有可能组合的结果。如果main_ingredient表中存在任何组合,那么您将获得相应的计数,否则您将获得recipes作为计数。

0

您可以选择此查询的较短版本:

SELECT 
method_ingredients.method_id,
method_ingredients.ingredients_id,
COUNT(R.method) AS cnt
FROM 
(
    SELECT 
    TM.id AS method_id,
    TMI.id AS ingredients_id
    FROM tbl_methods TM
    CROSS JOIN tbl_main_ingredients TMI
) AS method_ingredients
LEFT JOIN `recipes` R ON R.method = method_ingredients.method_id AND R.main_ingredient = method_ingredients.ingredients_id
GROUP BY method_ingredients.method_id, method_ingredients.ingredients_id
ORDER BY method_ingredients.method_id, method_ingredients.ingredients_id;

更多

关于SELECT TM.id AS method_id, TMI.id AS ingredients_id, COUNT(R.method) AS cnt FROM tbl_methods TM CROSS JOIN tbl_main_ingredients TMI LEFT JOIN `recipes` R ON R.method = TM.id AND R.main_ingredient = TMI.id GROUP BY TM.id, TMI.id ORDER BY TM.id, TMI.id; 的一些细微之处:

COUNT

SQL FIDDLE

BTW 在您的用例中与SELECT COUNT(0); Result: 1 SELECT COUNT(-1); Result: 1 SELECT COUNT(NULL); Result: 0 SELECT COUNT(71); Result: 1 无关。如果有COALESCE,则COALESCE会从列表中返回第一个non-NULL元素。

示例:

NULL

答案 1 :(得分:0)

您可能需要检查main_ingredient是否为空

SELECT method, ifnull(main_ingredient,0), COUNT(*) AS cnt FROM  `recipes` 
GROUP BY  method

答案 2 :(得分:0)

交叉加入你的2个基表,然后在int *arr; int sizeOfArr = 0; printf("Enter size of arr.\n"); scanf("%d", &sizeOfArr); arr = malloc(sizeOfArr * sizeof(int)); for (int i = 0; i < sizeOfArr; i++) { scanf("%d", &arr[i]); //notice the diff here } 上离开联接。然后,如果您计算任何左连接列,您将得到所需的结果:

recipes