我编写了一个复杂的SQL查询(正确运行):
select user.id,user.name,profile.info,score.ammount
from user,profile,score
where email = 'example@email.com'
AND user.id = profile.user_id
AND user.id = score.user_id
AND profile.type = 'language'
AND score.type = 'amount'
此查询将返回:
[id] => 10002096
[name] => Erik
[info] => English
[ammount] => 510710
问题是如果user.id与profile.user_id不匹配,之前匹配的结果如(user.id,user.name)没有返回? (即使未找到下一场比赛,我也要退回)
如果不匹配则想要返回类似的内容:
[id] => 10002096
[name] => Erik
如何解决这个问题?
个人资料表样本:
id user_id type info
1 1 language english
2 1 admin top
3 2 likes football
4 3 likes -
5 3 language english
id = 2的用户没有语言
答案 0 :(得分:2)
尝试离开加入表而不是获取笛卡尔积和过滤..这是连接表的旧ansi方式,并且在添加更多表时更难处理。
SELECT u.id, u.name, p.info, s.ammount
FROM user u
LEFT JOIN profile p ON p.user_id = u.id AND p.type = 'language'
LEFT JOIN score s ON s.user_id = u.id AND s.type = 'amount'
WHERE email = 'example@email.com'
基本上左连接表示加入信息,如果有不匹配的行,则不要过滤