我有一种情况,可以说我正在尝试获取有关某些食物的信息。然后我需要显示所有信息以及该食物中的所有成分。
通过我的查询,我得到了一个数组中的所有信息,但只有第一个成分......
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingredient = 1
ingAmount = 2
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
我想拿回这样的东西......
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingArr = {ingredient: 1, ingAmount: 4}, {ingredient: 3, ingAmount: 2}, {ingredient: 5, ingAmount: 1}
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
这是我现在正在使用的查询。我如何调整它以返回食物 ID 4,然后还获得该食物的所有成分?一直在做其他事情,比如获得食物的平均评分?
谢谢!
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, c.ingredient, c.ingAmount, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM `foods` a
LEFT JOIN `foods_ratings` b
ON a.foodId = b.foodId
LEFT JOIN `foods_ing` c
ON a.foodId=c.foodId
WHERE a.foodId=4
编辑:
Catcall 引入了我从未听说过的“子查询”的概念,因此我正在尝试进行这项工作,看看我是否可以轻松地在 1 个查询中做到这一点。但我只是不断收到错误的回报。这就是我没有运气的尝试..
//I changed some of the column names to help them be more distinct in this example
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM foods a
LEFT JOIN foods_ratings b ON a.foodId = b.foodId
LEFT JOIN (SELECT fId, ingredientId, ingAmount
FROM foods_ing
WHERE fId = 4
GROUP BY fId) c ON a.foodId = c.fId
WHERE a.foodId = 4";
编辑与 ROLANDS GROUP_CONCAT/JSON 想法相关的另外 1 件事作为解决方案 4 这个
我正在尝试确保我发送回我的 Flash 项目的 JSON 字符串已准备好被正确解析Invalid JSON parse input.
不断弹出..
所以我想我需要在正确的地方正确地使用所有的双引号。
但是在我的 MySQL 查询字符串中,我试图转义双引号,但是它使我的 mySQL 变量不起作用,例如......
如果我这样做..
GROUP_CONCAT('{\"ingredient\":', \"c.ingredient\", ',\"ingAmount\":', \"c.ingAmount\", '}')`
我明白这个...
{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount}
如何使用所有双引号使 JSON 正确形成而不破坏 mysql?