开发者

MySQL: Foreign Keys

Sorry if this is already answered somewhere, but how do i create a foreign key that is not always present.

Example: I have a table called invoice_payments with the INT columns 'type' and 'cc_gateway'. I also have a 2nd table cal开发者_如何学Goled invoice_cc_gateway. Since I can accept multiple payment types (cash, cc payments online) i store the type of payment in type (0=cash, 1=cc gateway), and when it is a payment from the gateway, I want to link to that specific item.

Now my problem is, I know how to link the two tables together if the key always exists, but what if the key won't always be present. If we have a cash payment, I set cc_gateway to 0, since it does not relate.

In the past I just created a dummy row for 0 inside cc_gateway so that my keys always match, but there must be a more correct way to do this.

Thanks in advance


Rephrased answer

Sorry, I was a bit quick before, of course you can have a foreign key in the Gateway-table that references the Items paid via gateway, but the opposite can not be true (ie a key in the Item table linking to the Gateway table)

If the key will not always be present it cannot be a foreign key constraint (references ), but instead you will have to join the gateway table when that value is present.

Example

select * from invoice_payments inv
left join invoice_cc_gateway gw
on inv.paymentId = gw.paymentId
where paymentType = 1
union
select * from invoice_payments
where paymentType = 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜