最近做的功能涉及这方面,算是练了一下。
首先多对一部分较简单。多的那一方表,多设置一个字段是少的那一方的id(主键)。
具体查询时候关联查询即可。
可设置外键进行级联操作。
具体以后做到这个功能再更新。
多对多:
设备和用户多对多,一个用户可有多台设备,一个设备可供多个用户使用。
首先设备表 dev:
用户表 user:
然后创建中间表user_dev 其中user_id 对应user表id dev_id对应dev表dev_id:
可以在user_dev表设置外键关联:
(这里添加外键,在我的理解是添加约束,还有级联。如果只是简单的查询一类的操作,外键未必有什么意义)
之后,在进行用户user表的存储操作时候,要注意同时进行user_dev表的存储操作。记录,该用户存在哪个设备上。
下面是查询的例子,要用到关联查询:
查询有用户35096037-941B-4934-9DB1-7DC5497A8DAF的所有设备:
SELECT dev.name FROM dev INNER JOIN user_dev ON user_dev.dev_id=dev.dev_id INNER JOIN user ON user.id='35096037-941B-4934-9DB1-7DC5497A8DAF' and user.id = user_dev.user_id;
查询设备2上的所有用户:
SELECT user.username FROM user INNER JOIN user_dev ON user_dev.user_id=user.id INNER JOIN dev ON dev.dev_id='2' and user_dev.dev_id = dev.dev_id;
之后具体有什么实践方面心得再更新。