Автор Тема: Можно ли упорядочить данные?  (Прочитано 5154 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« : 07 Февраля 2002, 13:05:31 »
Можно ли добиться упорядоченного хранения данный в таблице по двум полям? Например, есть поле "1" и поле "2". Мне нужно упорядочить записи сначала по первому, а потом по второму, т.е:

 1 | 2
 A | a
 A | c
 A | d
 B | a
 B | b
 B | c

и потом при вводе новой записи, добавлять ее не в конец таблицы, а с учетом упорядоченности. Т.е. запись (\'A\',\'b\') будет добавлена между записями (\'A\',\'a\') и (\'A\',\'c\').
Как это реализовать?

Оффлайн fidget

  • Непоседа
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 607
  • +0/-0
  • 2
    • Просмотр профиля
    • http://
Можно ли упорядочить данные?
« Ответ #1 : 07 Февраля 2002, 13:29:42 »
зачем тебе это????
Когда будешь выбирать данные из таблицы используй ODER BY поле_1, поле_2
На Машине Тьюринга далеко не уедешь.

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #2 : 07 Февраля 2002, 13:39:15 »
Цитировать
зачем тебе это????
Затем, что я в другом порядке все равно выводить данные не буду (это точно!). А при запросе теряется время на упорядочивание.

Оффлайн fidget

  • Непоседа
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 607
  • +0/-0
  • 2
    • Просмотр профиля
    • http://
Можно ли упорядочить данные?
« Ответ #3 : 07 Февраля 2002, 14:22:37 »
Создай индекс по 2м полям
CREATE INDEX myindex ON mytable (column1, column2);
На Машине Тьюринга далеко не уедешь.

Оффлайн vladsu

  • Фанат форума
  • Старожил
  • ****
  • Сообщений: 271
  • +0/-0
  • 0
    • Просмотр профиля
    • http://vladislavsurguchev.eu/
Можно ли упорядочить данные?
« Ответ #4 : 07 Февраля 2002, 14:26:27 »
Hi.

Это невозможно!!!

А для ускорения используйте индексы.
----------------------------------------------
Мой сайт чёрно-белых фотографий из разных уголков мира тут

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #5 : 07 Февраля 2002, 14:28:05 »
Создала. Дальше что? При обзоре (я phpmyadmin использую) все равно записи не упорядочены :(

Оффлайн Chs

  • Perl программер
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 1108
  • +0/-0
  • 2
    • Просмотр профиля
    • http://chs.now.at/
Можно ли упорядочить данные?
« Ответ #6 : 07 Февраля 2002, 14:28:50 »
Цитировать

Затем, что я в другом порядке все равно выводить данные не буду (это точно!). А при запросе теряется время на упорядочивание.


Column indexes
--------------

All *MySQL* column types can be indexed.  Use of indexes on the
relevant columns is the best way to improve the performance of `SELECT\'
operations.

A table may have up to 16 indexes.  The maximum index length is 256
bytes, although this may be changed when compiling *MySQL*.

For `CHAR\' and `VARCHAR\' columns, you can index a prefix of a column.
This is much faster and requires less disk space than indexing the
whole column.  The syntax to use in the `CREATE TABLE\' statement to
index a column prefix looks like this:

     KEY index_name (col_name(length))

The example below creates an index for the first 10 characters of the
`name\' column:

     mysql> CREATE TABLE test (
                name CHAR(200) NOT NULL,
                KEY index_name (name(10)));

For `BLOB\' and `TEXT\' columns, you must index a prefix of the column,
you cannot index the entire thing.
2B OR NOT 2B = FF

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #7 : 07 Февраля 2002, 14:29:26 »
Цитировать
А для ускорения используйте индексы.
А как это работает?

Оффлайн Chs

  • Perl программер
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 1108
  • +0/-0
  • 2
    • Просмотр профиля
    • http://chs.now.at/
Можно ли упорядочить данные?
« Ответ #8 : 07 Февраля 2002, 14:43:28 »
Цитировать

А как это работает?

How *MySQL* uses indexes
========================

Indexes are used to find rows with a specific value of one column fast.
Without an index *MySQL* has to start with the first record and then
read through the whole table until it finds the relevent rows. The
bigger the table, the more this costs. If the table has an index for
the colums in question, *MySQL* can get fast a position to seek to in
the middle of the data file without having to look at all the data. If
a table has 1000 rows this is at least 100 times faster than reading
sequentially. Note that if you need to access almost all 1000 rows it
is faster to read sequentially because we then avoid disk seeks.

All *MySQL* indexes (`PRIMARY\', `UNIQUE\' and `INDEX\') are stored in
B-trees. Strings are automatically prefix- and end-space compressed.
*Note `CREATE INDEX\': CREATE INDEX.

Indexes are used to:
   * Quickly find the rows that match a `WHERE\' clause.

   * Retrieve rows from other tables when performing joins.

   * Find the `MAX()\' or `MIN()\' value for a specific indexed column.
          SELECT MIN(key_part2),MAX(key_part2) FROM table_name where key_part1=10

   * Sort or group a table if the sorting or grouping is done on a
     leftmost prefix of a usable key (e.g., `ORDER BY
     key_part_1,key_part_2 \'). The key is read in reverse order if all
     key parts are followed by `DESC\'.

     The index can also be used even if the `ORDER BY\' doesn\'t match
     gthe index exactly, as long as all the not used index parts and
     all the extra are `ORDER BY\' columns are constants in the `WHERE\'
     clause. The following queries will use the index to resolve the
     `ORDER BY\' part.

          SELECT * FROM foo ORDER BY key_part1,key_part2,key_part3;
          SELECT * FROM foo WHERE column=constant ORDER BY column, key_part1;
          SELECT * FROM foo WHERE key_part1=const GROUP BY key_part2;

   * In some cases a query can be optimized to retrieve values without
     consulting the data file. If all used columns for some table are
     numeric and form a leftmost prefix for some key, the values may be
     retrieved from the index tree for greater speed.

          SELECT key_part3 FROM table_name WHERE key_part1=1


Suppose you issue the following `SELECT\' statement:

     mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

If a multiple-column index exists on `col1\' and `col2\', the appropriate
rows can be fetched directly. If separate single-column indexes exist
on `col1\' and `col2\', the optimizer tries to find the most restrictive
index by deciding which index will find fewer rows and using that index
to fetch the rows.

If the table has a multiple-column index, any leftmost prefix of the
index can be used by the optimizer to find rows. For example, if you
have a three-column index on `(col1,col2,col3)\', you have indexed
search capabilities on `(col1)\', `(col1,col2)\' and `(col1,col2,col3)\'.

*MySQL* can\'t use a partial index if the columns don\'t form a leftmost
prefix of the index.  Suppose you have the `SELECT\' statements shown
below:

     mysql> SELECT * FROM tbl_name WHERE col1=val1;
     mysql> SELECT * FROM tbl_name WHERE col2=val2;
     mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

If an index exists on `(col1,col2,col3)\', only the first query shown
above uses the index. The second and third queries do involve indexed
columns, but `(col2)\' and `(col2,col3)\' are not leftmost prefixes of
`(col1,col2,col3)\'.

*MySQL* also uses indexes for `LIKE\' comparisons if the argument to
`LIKE\' is a constant string that doesn\'t start with a wildcard
character.  For example, the following `SELECT\' statements use indexes:

     mysql> select * from tbl_name where key_col LIKE "Patrick%";
     mysql> select * from tbl_name where key_col LIKE "Pat%_ck%";

In the first statement, only rows with `"Patrick" <= key_col <
"Patricl"\' are considered.  In the second statement, only rows with
`"Pat" <= key_col < "Pau"\' are considered.

The following `SELECT\' statements will not use indexes:
     mysql> select * from tbl_name where key_col LIKE "%Patrick%";
     mysql> select * from tbl_name where key_col LIKE other_col;

In the first statement, the `LIKE\' value begins with a wildcard
character.  In the second statement, the `LIKE\' value is not a constant.

Searching using `column_name IS NULL\' will use indexes if column_name
is an index.

*MySQL* normally uses the index that finds least number of rows. An
index is used for columns that you compare with the following operators:
`=\', `>\', `>=\', `<\', `<=\', `BETWEEN\' and a `LIKE\' with a non-wildcard
prefix like `\'something%\'\'.

Any index that doesn\'t span all `AND\' levels in the `WHERE\' clause is
not used to optimize the query. In other words:  To be able to use an
index, a prefix of the index must be used in every `AND\' group.

The following `WHERE\' clauses use indexes:
     ... WHERE index_part1=1 AND index_part2=2 AND other_column=3
     ... WHERE index=1 OR A=10 AND index=2      /* index = 1 OR index = 2 */
     ... WHERE index_part1=\'hello\' AND index_part_3=5
               /* optimized like "index_part1=\'hello\'" */
     ... WHERE index1=1 and index2=2 or index1=3 and index3=3;
               /* Can use index on index1 but not on index2 or index 3 */

These `WHERE\' clauses do *NOT* use indexes:
     ... WHERE index_part2=1 AND index_part3=2  /* index_part_1 is not used */
     ... WHERE index=1 OR A=10                  /* Index is not used in both AND parts */
     ... WHERE index_part1=1 OR index_part2=10  /* No index spans all rows */

Note that in some cases `MySQL\' will not use an index, even if one
would be available.  Some of the cases where this happens are:

   * If the use of the index, would require *MySQL* to access more than
     30 % of the rows in the table.  (In this case a table scan is
     probably much faster as this will require us to do much fewer
     seeks).  Note that if you with such a query use `LIMIT\' to only
     retrieve part of the rows, *MySQL* will use an index anyway as it
     can this way much more quickly find the few rows to return in the
     result.
2B OR NOT 2B = FF

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #9 : 07 Февраля 2002, 15:04:34 »
Спасибо

Оффлайн Chs

  • Perl программер
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 1108
  • +0/-0
  • 2
    • Просмотр профиля
    • http://chs.now.at/
Можно ли упорядочить данные?
« Ответ #10 : 07 Февраля 2002, 15:20:39 »
Цитировать
Спасибо

Не за что. Как говорят - читайте доку, бо она рулез.:)
2B OR NOT 2B = FF

Оффлайн Tepncuxopa

  • Муза форума
  • Глобальный модератор
  • Старожил
  • *****
  • Сообщений: 386
  • +0/-0
  • 1
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #11 : 07 Февраля 2002, 16:13:14 »
Цитировать
читайте доку, бо она рулез
Рулез-рулезом, но из-за нехватки времени до нее руки не доходят. К сожалению :(
Получается так, что лучше задать вопрос на форуме, получить ответ и копать уже в том направлении, какое посоветовали. Спасибо, хоть есть у кого спросить :)

Оффлайн Flash

  • Виртуоз...
  • Ветеран
  • *****
  • Сообщений: 661
  • +0/-0
  • 2
    • Просмотр профиля
Можно ли упорядочить данные?
« Ответ #12 : 11 Февраля 2002, 12:42:37 »
Цитировать
Получается так, что лучше задать вопрос на форуме, получить ответ и копать уже в том направлении, какое посоветовали. Спасибо, хоть есть у кого спросить

Это точно :)
Почему так всегда: мозги утекают, а доноры остаются?

 

Sitemap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28