简体   繁体   English

MySQL的联接和空

[英]mysql join and null

I have 2 tables "browsers" and "votes". 我有2个表格“浏览器”和“投票”。 I need all the browsers and only the votes by a vote_ranking and a user_id. 我需要所有浏览器,并且只需要vote_ranking和user_id的票即可。 Sometimes there is no votes but i still need the browsers. 有时没有选票,但我仍然需要浏览器。 That's the code i wrote: 那就是我写的代码:

SELECT browsers.*, votes.*
FROM browsers LEFT JOIN votes ON browsers.app_id = votes.app_id
WHERE vote_ranking = '$ranking' AND user_id = $userid or vote_id IS NULL

The problem is when there is no votes (vote_id IS NULL) the app_id is changed to NULL. 问题是当没有投票时(vote_id IS NULL),app_id更改为NULL。 But i need to keep the browsers app_id even there's no app_id in votes. 但是,即使没有app_id投票,我也需要保持浏览器app_id。

Can i join the table votes only on rows where the're is a vote_id ? 我可以只在有一个表决ID的行上加入表表决吗? Or anything similar to do what i need ? 或任何类似的事情来满足我的需求?

Thanks 谢谢

Try this: 尝试这个:

SELECT browsers.*, votes.vote_ranking, votes.user_id
FROM browsers
LEFT JOIN votes
  ON browsers.app_id = votes.app_id
  AND vote_ranking = '$ranking' 
  AND user_id = $userid

This way, a corresponding record from votes will be joined only if it has appropriate vote_ranking. 这样, 只有当投票记录具有适当的vote_ranking时,投票的相应记录才会被加入。 Otherwise there will be NULL s, but you will still keep the data from browsers . 否则将存在NULL ,但是您仍将保留来自browsers的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM