问题
I have two tables:
items bids
-id (pk) -id (pk)
-user_id (fk) -user_id (fk) references users (pk)
-title -item_id (fk) references items
-bid_price
I also want the option for user to accept the bid. How should I structure the database to have this facility.
Option 1:
bids
-id (pk)
-user_id
-item_id
-bid_price
-is_accepted
Option 2:
items
-id
....
-accepted_bid_id (fk references bid)
Which option should I take or suggest me other options ?
回答1:
If there is only one accepted bid per item, Option 2 would be the better way. Option 1 would allow for any amount of bids to be accepted.
A bit more on the reasoning: The accepted_bid_id
column in Option 2 not only ensures that there only is a maximum of one accepted bid per item, it also lets you access that bid quicker. If you used booleans (your Option 1), you'd have to do something like this to join on the accepted bid:
SELECT * FROM items
LEFT JOIN bids ON bids.item_id=items.id AND bids.is_accepted
This requires a compound index on bids (item_id,is_accepted) to be reasonably fast. With Option 2 on the other hand, you can do this:
SELECT * FROM items
LEFT JOIN bids ON bids.id = items.accepted_bid_id
This does not require any index apart from the two primary keys you already have.
So to sum it up:
- Option 2 maintains integrity
- Option 2 does not require additional indexes
- Option 2 allows simpler queries
So there isn't mucht that points in the direction of Option 1.
来源:https://stackoverflow.com/questions/15323646/database-structure-for-bidding-site