简体   繁体   English

SQL:使用两个索引创建表

[英]SQL: Create table with two indexes

I previously created a table using the following SQL code: 我以前使用以下SQL代码创建了一个表:

CREATE TABLE myTable (
    id_A BIGINT NOT NULL,
    id_B INT NOT NULL,
    some_info varchar(255),
    some_info2 varchar(255),
    PRIMARY KEY (id_A) 
)

In the previous table created, both id_A and id_B would be unique values. 在创建的上一个表中,id_A和id_B均为唯一值。 I understand that id_A is forced to be unique by the PRIMARY KEY (id_A) code, which is perfect (which also indexes it), however id_B isn't 我了解到,PRIMARY KEY(id_A)代码强制id_A是唯一的,这是完美的(也可以对其进行索引),但是id_B不是

Here is where I am confused. 这是我感到困惑的地方。 id_B will also be unique, however I am not sure how to force it to be unique in the table,and how to make the database create an index for it so that future queries that use SELECT on this table will have good preformance. id_B也将是唯一的,但是我不确定如何强制它在表中是唯一的,以及如何使数据库为其创建索引,以便将来在此表上使用SELECT的查询具有良好的性能。 I know I can't have two PRIMARY KEYS: 我知道我不能有两个主键:

PRIMARY KEY (id_A) 
PRIMARY KEY (id_B) 

How might I go about making an index for id_B as well so that future queries happen efficiently? 我又该如何为id_B编制索引,以便将来有效地进行查询?

You can add a UNIQUE INDEX on the column. 您可以在列上添加UNIQUE INDEX While a table can only have one PRIMARY KEY , it can have as many UNIQUE INDEX es as you might need. 虽然一个表只能有一个PRIMARY KEY ,但是它可以具有所需的UNIQUE INDEX个数。

ALTER TABLE myTable
ADD UNIQUE INDEX `UI_myTable_idB` (`id_B` );

You can use the MySQL UNIQUE KEY for the column. 您可以将MySQL UNIQUE KEY用于该列。 This will force the values in the id_B column to be unique, but not use it as the primary key column. 这将强制id_B列中的值唯一,但不能将其用作主键列。 You can achieve it with this statement: 您可以使用以下语句实现它:

CREATE TABLE myTable (
id_A BIGINT NOT NULL,
id_B INT NOT NULL,
some_info varchar(255),
some_info2 varchar(255),
PRIMARY KEY (id_A),
UNIQUE KEY (id_b))

This will automatically index the column like you want it to. 这将自动为您希望的列编制索引。 Primary keys and unique keys in a MySQL table are essentially the same, except a primary key cannot be NULL, and there can be only one primary key column (or combination of primary key columns). MySQL表中的主键和唯一键基本相同,不同之处在于主键不能为NULL,并且只能有一个主键列(或主键列的组合)。 There can be any number of unique key columns. 可以有任意数量的唯一键列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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