如何为MySQL数据表的字段添加MUL键?
Add MUL Keys to Your Table Structure
Got it, let's break this down. In MySQL, the MUL key label means a non-unique index—this lets you have duplicate values in the field while still speeding up queries that filter or sort on it. Perfect for a likes table where multiple users can like the same post, and one user can like multiple posts.
Here's what your modified table structure will look like once you add the indexes:
+-------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | post | int(11) | NO | MUL | NULL | | | liker | int(11) | NO | MUL | NULL | | +-------+---------+------+-----+---------+----------------+
To update your existing table to this structure, run the following ALTER TABLE command (replace your_table_name with the actual name of your table):
ALTER TABLE your_table_name ADD INDEX idx_post (post), ADD INDEX idx_liker (liker);
Quick tips:
- The
idx_postandidx_likernames are just examples—feel free to use more descriptive names (likepost_referenceifpostlinks to apoststable, oruser_liker_indexfor clarity). - These indexes will drastically speed up common queries like
SELECT * FROM your_table_name WHERE post = 123(to get all likes for a post) orCOUNT(*) FROM your_table_name WHERE liker = 456(to count how many posts a user has liked), especially as your table grows with more data.
内容的提问来源于stack exchange,提问作者Babr




