且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将外键引用到多个表的主键

更新时间:2023-01-29 09:36:00

Table1有两个外键cust_id和branch_id:

Table1 having two foreign keys cust_id and branch_id:
create table loan_details(branch_id int(5), cust_id int(5), amount int(10), foreign key(branch_id) references branch_details(branch_id), foreign key(cust_id) references cust_details(cust_id));





表2有主键cust_id:



Table2 having primary key cust_id:

create table cust_details(cust_id int(5), cust_name varchar(25),primary key(cust_id));





具有主键branch_id的表3:



Table3 having primary key branch_id:

create table branch_details(branch_id int(5), branch_name varchar(25),primary key(branch_id));





从中选择使用自然连接的3个表:



Selection from 3 tables using natural join:

SELECT cust_id,cust_name,amount FROM cust_details c JOIN loan_details l ON c.cust_id=l.cust_id JOIN branch_details b ON l.branch_id=b.branch_id;


表2和表3具有多对多的关系,例如:

1.教师(表1)可以教授多个班级(表2)和一个班可以由mo教授不是一位老师。

2.顾客(表1)可以购买任意数量的产品(表2),产品可以由任意数量的顾客购买。

要链接这两个表,您需要第三个表(表1)将它们组合在一起。该表至少有2个字段,每个字段链接到相应表的主键。一个例子:

Table 2 and table 3 are having many-to-many relationship, for example:
1. a teacher (table 1) may teach more than one class (table 2) and a class may be taught by more than one teacher.
2. a customer (table 1) may buy any number of products (table 2) and a product may be bought by any number of customers.
To link these 2 tables, you need a third table (table 1) to pull them together. This table will have at least 2 fields, one each linking to the primary keys of the respective tables. One example:
Table Name      Columns
tbl_customer    cust_id (primary key)
                cust_name 
tbl_product
                product_id (primary key)
                product_name
                price
tbl_order
                order_id (primary key)
                cust_id (foreign key to tbl_customer)
                product_id (foreign key to tbl_product)



要查找特定的订单明细,您必须将它们加在一起:


To find a particular order detail, you have to JOIN them together:

select order_id, cust_name, product_name, price from tbl_customer c join tbl_order o on c.cust_id = o.cust_id join tbl_product p on p.product_id = o.product_id where order_id=2



参考:

1. http://www.datanamic.com/support/lt-dez005-introduction- db-modeling.html [ ^ ]

2. SQL连接的可视化表示 [ ^ ]


key实际上并不重要一个连接点,它们用于强制约束,即如果你删除了一个客户那么约束可以删除包含该customer_id的所有订单。



可以加入任何东西,只需了解内部和外部联接之间的差异。
key's don't actually matter one jot for joins, they are used for enforcing constraints i.e. if you delete a customer then the constraint can delete all the orders that contain that customer_id.

can join anything to anything though, just learn the differences between inner and outer joins.