You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为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_post and idx_liker names are just examples—feel free to use more descriptive names (like post_reference if post links to a posts table, or user_liker_index for 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) or COUNT(*) 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

火山引擎 最新活动