[英]Mysql select rows comaparing with another table records
Ok, so I have a table that contains optionID, optionName. 好的,所以我有一个包含optionID,optionName的表。 Its called user_options.
它称为user_options。 I have a second table that contains userID, optionID.
我有第二个表,其中包含用户ID,optionID。 Its called user_selected_options.
它称为user_selected_options。
Options in user_options are stored for a user in user_selected_options, which is fine. user_options中的选项是为用户存储在user_selected_options中的,这很好。 Now, when editing a user, I just want to show the options from user_options which are not selected for that user in user_selected_options as select boxes.
现在,在编辑用户时,我只想显示user_options中未为该用户选择的user_options中的选项作为选择框。 How can I do this?
我怎样才能做到这一点?
I hope this question make sense. 我希望这个问题有意义。 Please let me know if it is unclear and I will explain further.
如果不清楚,请告诉我,我将进一步解释。
Thanks for any tips. 感谢您的提示。
Here is one method using not exists
: 这是一种
not exists
方法:
select uo.*
from user_options uo
where not exists (select 1
from user_selected_options uso
where uso.optionId = uo.option_id and uso.userId = $userId
);
For best performance, create an index on user_selected_options(option_id, userId)
. 为了获得最佳性能,请在
user_selected_options(option_id, userId)
上创建一个索引。
you can use from not in command of mysql for example: 您可以使用非命令的mysql例如:
select * from user_options where optionID NOT IN(select optionID from user_selected_options where userID=10)
see more examples about NOT IN http://www.w3resource.com/mysql/comparision-functions-and-operators/not-in.php 查看有关NOT IN的更多示例http://www.w3resource.com/mysql/comparision-functions-and-operators/not-in.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.