How to have a one-to-one relation to either one of two other tables

database-design

Suppose I have three tables

  • orders table, fields: name, address, country, paid, shipped, amount
  • paypal payment table, fields: order_id
  • stripe payment table, fields: customer_id, cvc_valid, address_valid, zip_valid

Each order should be associated with only one payment table, paypal or stripe

Question is: How do I associate an Order with its payment when it is possible that the payment is either in the Paypal table or in the Stripe table?

I thought of adding an enum field to the Orders table to decide whether to look up the payment in the Paypal table or to look up in the Stripe table. Are there better methods than this?

I would like to use either MariaDB, MySQL, or SQLite.

Best Answer

There are several options:

  1. Combine Paypal and Stripe tables into a single Payment table, with fields to hold either type of payment;
  2. Have both a paypal_id and a stripe_id in the Order table; use a condition on the table to ensure that at least one of them is NULL.
  3. Have a single Payment_ID with a flag to indicate whether it's an id from Paypal or Stripe as you propose.

The first two options allow for the payment ID(s) to be foreign keys to the payment table(s), the third does not.

I would lean towards a single table with all payment data, but that may be a personal preference. Which of the first two options is better would depend on whether there are any common columns between Paypal and Stripe, and just how large the distinct columns are.

UPDATE: joanolo's answer lays out how to actually implement my option 2; take a look!