CREATE TABLE subscription ( magazine_id bigint,user_id bigint,PRIMARY KEY (magazine_id,user_id) ) CREATE TABLE delivery ( magazine_id bigint,FOREIGN KEY (subscription) REFERENCES subscription (magazine_id,user_id) )
查询特定订阅的交货方式是什么?有没有办法将列名分配给PRIMARY KEY(magazine_id,user_id)和相应的外键,以便我可以这样查询
SELECT * FROM subscription JOIN delivery ON (delivery.subscription_fk = delivery.subscription_pk)
注意:我可以写这样的东西:
SELECT * FROM subscription JOIN delivery ON (delivery.magazine_id = subscription.magazine_id AND delivery.user_id = subscription.user_id)
但是,我的印象是,实现这一点的方法不那么冗长.
解决方法
有一个NATURAL JOIN:
SELECT * FROM subscription NATURAL JOIN delivery
NATURAL
NATURAL
is shorthand for aUSING
list that mentions all columns in the two tables that have the same names.
它将适用于您的测试设置,但它不是严格执行您要求的.连接基于所有共享相同名称的列.不考虑外键.
简化代码/较少冗长
对于初学者,您可以使用表别名,并且您不需要使用ON(与USING不同)的连接条件下的括号:
SELECT * FROM subscription s JOIN delivery d ON d.magazine_id = s.magazine_id AND d.user_id = s.user_id;
由于连接条件中的列名称相同,因此可以使用USING进一步简化:
SELECT * FROM subscription s JOIN delivery d USING (magazine_id,user_id);