简体   繁体   中英

Can I use either commands in MySQL? INDEX and FOREIGN KEY

So I am assigning foreign key and wanted to know which is better to use index or foreign key

This one:

CREATE TABLE meeting (
    meeting_id INT(11) NOT NULL PRIMARY KEY,
    room_id INT(11),
    name TINYTEXT,
    date DATE,
    FOREIGN KEY(room_id) REFERENCES room(room_id)
);

Or this one:

CREATE TABLE meeting (
    meeting_id INT(11) NOT NULL PRIMARY KEY,
    room_id INT(11),
    name TINYTEXR,
    date DATE,
    INDEX(room_id)
);

index and foreign key are two different things.

A foreign key means a meeting can't have a room_id value that doesn't appear in room 's room_id column.
An index means that you can query meetings by room_id much more efficiently, without having to scan the entire table.

If both meeting and room are fairly large, and you have several queries combining them (either by joins or subqueries), I'd have both the index and the foreign key .

Foreign Keys and Indexes are very different things.

You add the foreign key to enforce integrity of your data. You're saying, room_id is only ever allowed to be a number from room.room_id. It's a great property to have and you should always try to use them where possible.

You add the index to tell the database how you're going to be searching for data so that it can prepare the necessary datastructures to do that efficiently. In this case, once you add the index queries searching for meetings in specific rooms will be fast.

The two concepts are really totally unrelated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM