Search the MySQL manual:
MySQL Manual

Buy this Reference Manual in softcover from Barnes & Noble!

Previous / Next / Up / Table of Contents

6.5.7 Синтаксис оператора CREATE INDEX

CREATE [UNIQUE|FULLTEXT] INDEX index_name
        ON tbl_name (col_name[(length)],... )

Команда CREATE INDEX в версиях MySQL до 3.22 не выполняет никаких действий. В версии 3.22 и более поздних CREATE INDEX соответствует команде ALTER TABLE в части создания индексов. See section 6.5.4 Синтаксис оператора ALTER TABLE.

Обычно все индексы создаются в таблице во время создания самой таблицы командой CREATE TABLE. See section 6.5.3 Синтаксис оператора CREATE TABLE. CREATE INDEX дает возможность добавить индексы к существующим таблицам.

Список столбцов в форме (col1,col2,...) создает индекс для нескольких столбцов. Величины индексов формируются путем конкатенации величин указанных столбцов.

Для столбцов типов CHAR и VARCHAR с помощью параметра col_name(length) могут создаваться индексы, для которых используется только часть столбца (для столбцов BLOB и TEXT нужно указывать длину). Команда, приведенная ниже, создает индекс, используя первые 10 символов столбца name:

mysql> CREATE INDEX part_of_name ON customer (name(10));

Поскольку большинство имен обычно имеют отличия друг от друга в первых 10 символах, данный индекс не должен быть намного медленнее, чем созданный из столбца name целиком. Кроме того, используя неполные столбцы для индексов, можно сделать файл индексов намного меньше, а это позволяет сэкономить место на диске и к тому же повысить скорость операций INSERT!

Следует учитывать, что в версии MySQL 3.23.2 и более поздних для таблиц типа MyISAM можно добавлять индекс только для столбцов, которые могут принимать величины NULL или для столбцов BLOB/TEXT.

Чтобы получить более подробную информацию о том, как MySQL использует индексы, See section 5.4.3 Использование индексов в MySQL.

С помощью опции FULLTEXT можно индексировать только столбцы VARCHAR и TEXT и только в таблицах MyISAM. Эта возможность доступна только в версии MySQL 3.23.23 и выше. See section 6.8 Полнотекстовый поиск в MySQL.

User Comments

Posted by on Wednesday December 18 2002, @5:27pm [Delete] [Edit]

It would be useful If I could set a character set
for the input file. For example I'm importing a
CSV file in DOS charset into a windows based
mySQL Database. German umlauts get lost at the
moment.
I'm thinking of a construct like 'load data
infile ... into table ... using charset
DOS'

Posted by on Friday May 17 2002, @6:24am [Delete] [Edit]

Has anyone ever considered adding support for
other decimal limiters then a "." in float
columns? I always get Decimal's in a CSV as
12345,76 and it is always a bit unnerving to
replace all kommas with points.

Posted by [name withheld] on Friday May 17 2002, @6:24am [Delete] [Edit]

We're using the PerlDBI with Mysql. In those cases
where we've had to create databases we've either checked for their existence by issuing a "show databases" and looking for the databasename in the resultset, or by just issuing the create command (without the if not exist part).

If an error is returned to perl/DBI, well then the database already existed, and if no error is return, well then we've successfully created the database.

The second solution is probably not adviseable to professional systems, and the first should have more wrapping (ie. if we cant create the database, try to detect why and report the result somewhere suitable).

Posted by on Wednesday December 18 2002, @5:27pm [Delete] [Edit]

To do a Group By and Order By with a count use the 'AS'
select student.student_name,COUNT(*) AS total_number
from student,course
where student.student_id=course.student_id
GROUP BY student_name
ORDER BY total_number;

Posted by on Friday May 17 2002, @6:24am [Delete] [Edit]

To get the time between two DATETIME values, convert the DATETIME values to a UNIX_TIMESTAMP (which is in seconds) - subtract the smaller from the larger and use SEC_TO_TIME to convert it to a time. I.E.
SELECT SEC_TO_TIME( UNIX_TIMESTAMP( '2000-10-25 17:45:12' ) - UNIX_TIMESTAMP( '2000-10-24 20:00:00' ) );
gives "21:45:12".

Posted by on Friday May 17 2002, @6:24am [Delete] [Edit]

I am currently transferring my websites to a new
host, and they use mySQL version 3.23.21-beta-log.
There seems to be a problem with the implementation
of escape characters, mainly \' inside single
quotes, and \" inside double quotes. For example,
both of the following cause errors:
'hap\'py' and "hap\"py"
All other escape sequences seem OK. Has there
perhaps been a change in which escape sequences are
allowed? Thanks

Posted by Calin Damian on Friday May 17 2002, @6:24am [Delete] [Edit]

It will be usefull to have a function with the oposite effect of date_format. Example:
I want to insert a datetime field into a table. The format of the string is '%m/%d/%y %h:%m%p'. More explicit:
11/23/00 05:23PM. Is there any solution for that?

Posted by on Thursday December 19 2002, @4:10pm [Delete] [Edit]

There is an inconsistancy with the UNSIGNED and
ZEROFILL options for the floating point and
decimal column types (compare to
http://www.mysql.com/doc/en/Column_types.html).
Through experimentation I found that these
options are allowed, but ignored. Very strange.

Posted by on Wednesday December 18 2002, @5:27pm [Delete] [Edit]

I tried this today on MySQL 3.23.32 and got
something unexpected
(to my line of thinking)

CREATE TABLE IF NOT EXISTS newtable SELECT id,
name FROM oldtable;

CREATE TABLE IF NOT EXISTS newtable SELECT id,
name FROM anothertable;

Instead of doing nothing, the second statement
appended the data that was selected from
anothertable onto the end of newtable.

Posted by on Friday May 17 2002, @6:24am [Delete] [Edit]

Suggestion for LOAD DATA enhancement: Allow the
use of something like a LIMIT statement, so that
one can easily load a section of a file (e.g.
lines 200-300). I'm trying to import a 10
million line file, and it takes all weekend.
Rather than chunking it exterally, I'd like to
load the data in smaller chunks. I realize that
technically this would be slower.

LOAD DATA INFILE "myfile.txt" LIMIT 200000,
100000;
LOAD DATA INFILE "myfile.txt" LIMIT 300000,
100000;

etc.

Posted by on Thursday August 15 2002, @2:29am [Delete] [Edit]

To remove duplicate records from a table you can
use the following query:

ALTER IGNORE TABLE table_name ADD UNIQUE
index_name (column_a, column_b, ... );

MySQL will prompt with the total number of records
and the number of duplicate records wich will be
deleted.

Add your own comment.

Top / Previous / Next / Up / Table of Contents