我有以下查询:
INSERT INTO kitchen (account_id, ingredient)
SELECT
kitchen.account_id,
ingredients.ingredient,
kitchen.ingredient,
count(*) c
FROM planned_meals
JOIN meal
JOIN kitchen
JOIN ingredients
WHERE planned_meals.mid = meal.mid
AND ingredients.rid = meal.recipe_id
AND ingredients.ingredient != ""
AND ingredients.ingredient NOT LIKE CONCAT("%",kitchen.ingredient,"%")
GROUP BY ingredients.ingredient
HAVING c = (SELECT count(*) FROM kitchen);
当我单独运行选择部分时,我得到:
作为c列的结果,我收到错误,因为它与INSERT INTO函数中的字段数冲突。
如何使select查询省略c列以使INSERT INTO正常工作?我不能使列数相同,因为我需要count列才能使我的HAVING函数工作
答案 0 :(得分:0)
插入时,您已定义了2列(account_id, ingredient)
,而您提供了4列kitchen.account_id, ingredients.ingredient, kitchen.ingredient, count(*) c
。您可以从select中删除不想插入的列
INSERT INTO kitchen (account_id, ingredient)
SELECT kitchen.account_id, ingredients.ingredient
FROM planned_meals JOIN meal JOIN kitchen JOIN ingredients WHERE planned_meals.mid = meal.mid AND ingredients.rid = meal.recipe_id AND ingredients.ingredient != "" AND ingredients.ingredient NOT LIKE CONCAT("%",kitchen.ingredient,"%")
GROUP BY ingredients.ingredient
HAVING count(*) = (SELECT count(*) FROM kitchen);