我有两个单独的查询,我想要合并。
SELECT e.id, e.measurement, e.name, weight, time, reps, distance, exerciseid, DATE(date) as date
FROM `users exercises` LEFT JOIN exercises as e ON e.id = exerciseid
WHERE `userid` = '24' AND `date` < now()
ORDER BY date DESC LIMIT 100
SELECT f.id, f.name, f.calories, f.protein, f.carbohydrate, DATE(date) as date, value, meal, unit
FROM `users foods` LEFT JOIN foods as f ON f.id = foodid
WHERE `userid` = '24' AND `date` < now()
ORDER BY date desc LIMIT 100
输出:
Array
(
[id] => 489
[measurement] => 2
[name] => Dumbbell Stability Ball Press
[weight] => 20
[time] =>
[reps] => 20
[distance] =>
[exerciseid] => 489
[date] => 2013-08-01
)
Array
(
[id] => 7
[name] => Cheese, camembert
[calories] => 300
[protein] => 19.8
[carbohydrate] => 0.46
[date] => 2013-09-20
[value] => 23
[meal] => 3
[unit] => 2
)
是否可以在保持相同输出的同时将它们组合起来?
编辑:对不起,我不清楚。我不想一起加入这些查询,我不是之后:Array
(
[id] => 672
[measurement] => 1
[name] => Ab Wheel (standing)
[weight] =>
[time] =>
[reps] => 5
[distance] =>
[exerciseid] => 672
[fid] => 23
[fname] => Cheese, gruyere
[calories] => 413
[protein] => 29.81
[carbohydrate] => 0.36
[value] => 54
[meal] => 1
[unit] =>
)
我想保持数组与原始数组相同,但我不想使用两个查询,而只想使用一个。如果可能的话。
答案 0 :(得分:1)
假设这里有一些东西,但如果他们共享用户标识,你可以将所有这些表加在一起
SELECT e.id, e.measurement, e.name, weight, time, reps, distance, exerciseid,
ue.DATE(date) as date, f.id, f.name, f.calories, f.protein, f.carbohydrate, uf.value,
uf.meal, uf.unit
FROM `users exercises`
LEFT JOIN exercises as e ON e.id = exerciseid
LEFT JOIN `user foods` as uf ON uf.userid = e.userid
LEFT JOIN `foods` as f ON f.userid = e.userid
WHERE `userid` = '24' AND `date` < now()
ORDER BY date DESC LIMIT 100
答案 1 :(得分:0)
当然您仍然可以加入更多表格,只需确保为表格提供正确的识别参数即可。未经测试的远射:
SELECT e.id, e.measurement, e.name, weight, time, reps, distance, exerciseid, DATE(date) as date,
f.id, f.name, f.calories, f.protein, f.carbohydrate, DATE(date) as date, value, meal, unit
FROM `users exercises`
LEFT JOIN exercises as e ON
e.id = exerciseid
INNER JOIN `users foods` ON
`users foods`.userid = `users exercises`.userid
LEFT JOIN foods as f ON
f.id = foodid
WHERE `users exercises`.`userid` = '24' AND `users exercises`.`date` < now()
ORDER BY date DESC LIMIT 100
我认为这两个表由userid链接就足够了,但由于我不知道内容,我无法确定日期。
答案 2 :(得分:0)
这是我的解决方案:
(
SELECT 'e' AS type,
exerciseid as id,
DATE(date) as date,
e.name,
weight,
time,
reps,
distance,
e.measurement,
null as value,
null as meal,
null as unit,
null as calories,
null as protein,
null as carbohydrate
FROM `users exercises`
LEFT JOIN exercises as e ON e.id = exerciseid
WHERE `userid` = $user->id AND `date` < now()
ORDER BY date desc
)
UNION ALL
(
SELECT 'f' AS type,
foodid as id,
DATE(date) as date,
f.name,
null as weight,
null as time,
null as reps,
null as distance,
null as measurement,
value,
meal,
unit,
f.calories,
f.protein,
f.carbohydrate
FROM `users foods`
LEFT JOIN foods as f ON f.id = foodid
WHERE `userid` = $user->id AND `date` < now()
ORDER BY date desc
)