我是mysql的新手。我有要求,请参阅下表
grand_score_master
autoid | user_id | package_id | grand_level | timestamp | timestring
55 | CBS_00002 | s78c_e4vt6 | 1 | ... | ...
58 | CBS_00002 | d47kndffqc | 3 | ... | ...
64 | CBS_00002 | d47kndffqc | 1 | ... | ...
65 | CBS_00002 | d47kndffqc | 2 | ... | ...
mega_score_master
autoid | user_id | package_id | mega_level | timestamp | timestring
1 | CBS_00002 | d47kndffqc | 1 | ... | ...
expected result
user_id | package_id | max_grand_leve | max_mega_level
CBS_00002 | s78c_e4vt6 | 1 | 0
CBS_00002 | d47kndffqc | 3 | 1
package_id
和user_id
在两个表格中。
我正在尝试进行查询,我将传递user_id说'CBS_00002',并且查询将返回max(grand_level)
和max(mega_level)
,方法是匹配/分组该用户的两个表中的公共package_id。 / p>
我试过这个
SELECT max(grand_score_master.grand_level),
grand_score_master.package_id,
max(mega_score_master.mega_level)
FROM grand_score_master
INNER JOIN mega_score_master
ON mega_score_master.package_id = grand_score_master.package_id
WHERE user_id='CBS_00002'
GROUP BY grand_score_master.package_id
但它仅返回 d47kndffqc 的结果,因为mega_score_master
需要一些帮助。
答案 0 :(得分:1)
你几乎就在那里,你只需要将inner join
改为left join
;这将保留第一个表中的所有行,无论是否在第二个表中匹配:
SELECT max(t1.grand_level) max_grand_level,
t1.package_id,
IFNULL(max(t2.mega_level), 0) max_mega_level
FROM grand_score_master t1
LEFT JOIN
mega_score_master t2
ON t2.package_id = t1.package_id
WHERE t1.user_id='CBS_00002'
GROUP BY t1.package_id
我还在表中添加了别名,以便查询结果更紧凑。