I've got a table in MySQL that has a Primary Key Column.
Lets say:
ID | Value
1 | One
2 | Two
6 | Three
8 | Four
9 | Five
How do I get it to be:
ID | Value
1 | One
2 | Two
3 | Three
4 | Four
5 | Five
There are no other tables. Just the one.
I just want the ID to be in a proper series.
Any suggestion??
A Query perhaps.. :)
There is even a simple way to accomplish the result by writing this query
SET #newid=0;
UPDATE tablename SET primary_key_id=(#newid:=#newid+1) ORDER BY primary_key_id;
This query will reindex the primary key starts from 1
Seems to me you have two options.
1) create a new table and copy the existing data over.
2) add another autoincrement field to the existing table, then delete the original column.
ALTER TABLE tableName ADD NewIdn INT NOT NULL AUTO_INCREMENT KEY
I did this in phpmyadmin by unchecking the A_I box (Auto Increment setting), clicking save, and then checking it again, and clicking save again.
Related
I have 2 tables in a my MySQL Database.
Let's call 1st main, 2nd final.
TABLE `main` has the structure | TABLE `final` has the structure
|
`id` --> PRIMARY KEY (Auto Increment) | `id` --> PRIMARY KEY (Auto Increment)
| `id_main` --> ?? (Need help here)
|
id | name | info | id | id_main | name | info(changed)
--------------------- | ---------------------------------------
1 | Peter | 5,9 | 1 | 2 | Butters | 0.3,34
2 | Butters | 3,3 | 2 | 4 | Stewie | 1.2,4.4
3 | Stan | 2,96 | 3 | 1 | Peter | 5.7,0.9
4 | Stewie | 1,84 | 4 | 3 | Stan | 4.8,0.74
After analysing data in main the results get put into final.
As you can see final has an extra column (id_main) which points back to main.id
In actuality these 2 tables are 100 million+ rows each, my problem arises while performing SQL queries.
How should final especially (id & id_main) be configured so that Querying from main to final is the fastest.
Can I do away with final.id (PRIMARY KEY, Auto Increment) & keep
final.id_main (As an UNIQUE Index?)
OR
Should I keep id AS PRIMARY KEY (AI) & final.id_main AS UNIQUE Index?
I would be making calls like:
int id_From_Main= 10000;
SELECT `id_main` FROM `final` WHERE `id`='"+id_From_Main+"'
If there's a 1:1 relation between those tables, I don't see any reason why they would need two separate auto-incremented primary keys.
I would remove the final.id column and have the final.id_main as a non-auto-incremented primary key and a foreign key to the main.id column.
In general, you can also have a table without a primary key at all. It depends on if you want to be able to select specific individual rows or not.
I don't understand your query SELECT id_main FROM final WHERE id = '"+id_From_Main+"' — you're trying to select the value of ID from main by ID from main. What's the purpose, why are you trying to get the value you already have?
Anyway, you're not providing enough information to give you a qualified answer. You have to optimize you data structures according to queries you'll be doing.
Make sure you have indexes on columns which you are using in the WHERE clausule. If you're selecting by final.id_main, have an index on that column. If you're selecting by final.id_main and final.name, have a composite index on both columns, etc.
Do you really need to have the name column in both tables? It's a bad database design, unless it's some performance optimization (to avoid a join).
So, you should:
collect all queries you're currently using, set proper indexes according to them
remove any unnecessary columns (e.g. final.id, final.name)
use the EXPLAIN on your queries to get execution information (you can also use the Explain analyzer to help you interpret the results)
you can try query profiling
In mysql, you have to define id as PK because it is auto_increment. Define id_main as UNIQUE.
The goal
Add from the 5th value.
The problem
There is a table on my database called markets. Within it, there are 5 values:
+----+------+
| Id | Name |
+----+------+
| 0 | NULL |
+----+------+
| 1 | A |
+----+------+
| 2 | B |
+----+------+
| 3 | C |
+----+------+
| 4 | D |
+----+------+
Id is a primary key and auto-incremented column and its start by zero (I added it manually to use as default). When I add some market to this table, seems that MySQL adds the market in question with 0 as Id — and I want to set the Id as 5 to continue the table's logic. So I ask: how can I add some value from the 5th Id?
What I've already tried
I already set the auto_increment value for 5, but without success. The query that I used is the following:
ALTER TABLE `markets` AUTO_INCREMENT = 5;
How do I know that the MySQL is attempting to add the market with its Id as 0?
My application is powered by C# that is throwing an exception:
Duplicate entry '0' for key 'PRIMARY'
On your INSERT statement, leave the auto_increment field out of the statement. This will leave MySQL to increment it and add it automatically.
how can I add some value from the 5th Id
Just try:;--
INSERT INTO markets(Name) VALUES('E');
ie, dont use the auto_increment field while inserting the data. MySQL is smart enough to do that for you ;)
Already there are four values are there in the table, So you can just insert next row. it will automatically take 5 as a next value.
When we are using auto_increment no need to specify that column in the insert command.
INSERT INTO markets(Name) VALUES('E');
In case if you want to alter the auto_increment value you can use the following statement
ALTER TABLE market AUTO_INCREMENT = 5;
I have a large database with two tables: stat and total.
The example of the relation is the following:
STAT:
| ID | total event |
+--------+--------------+
| 7 | 2 |
| 8 | 1 |
TOTAL:
|ID | Event |
+---+--------------+
| 7 | "hello" |
| 7 | "everybody" |
| 8 | "hi" |
This is a very simplified version; also consider that STAT table could have 500K records, and for each STAT I can have about 200 TOTAL rows.
Currently, if I run a simple SELECT query in table TOTAL the system is terribly slow.
Could anyone help me with some advice for the creation of the TOTAL table? Is it possible to say to MySQL that the id column is already sorted so that there is no reason to scan all the rows till the end where, for example, id=7?
Add INDEX(ID) to your tables (both), if you did not already.
SELECT COUNT(*) FROM TOTAL WHERE ID=7 -> if ID is indexed, this will be fast.
You can add an index, and furthermore you can partition your table.
As per #ypercube's comment, tables are not stored in a sorted state, so one cannot "tell" this to the database. However you can add an index on tables to make them faster to search.
One important thing to check - it looks like TOTAL.ID is intended as a foreign key - if so, the table TOTAL should have a primary key called ID. Rename the existing column of that name to STAT_ID instead, so it is obvious what it is a foreign key for. Then add an index on STAT_ID.
Lastly, as a point of style, I recommend that you make your table and column names case-insensitive, and write them in lower-case. It makes it easier to read SQL when keywords are in upper case, and database objects are in lower.
i'm trying to set up a MySQL database for storing biological data. I have to extract this data from a file and i have a perl script for that. The problem i have is that i need three primary keys in order for them to be unique, and i want one of them to be an auto increment integer. I would like, however, the auto-incremented value to reset each time the combination of the first two keys changes.
sequence1 | hit1 | 1
sequence1 | hit1 | 2
sequence1 | hit2 | 1
sequence2 | something | 1
sequence2 | something | 2
sequence2 | something | 3
sequence3 | something | 1
etc. etc.
is that possible or do i have to implement that directly into the script?
thank you
It is possible with MyISAM tables only and will not work in InnoDB or any other storage engine MySQL has.
Just create a primary key on (col1, col2, id) and set auto_increment flag on id column. And make sure there is no unique constraint on id alone. MyISAM will generate a new sequence of values per each unique pair of (col1, col2).
I have a table like the following,
| id | name | color |
------+--------+---------
| 1 | pear | green |
| 2 | apple | red |
| 3 | banana | yellow |
| 4 | grape | purple |
I'd like to reorder alphabetically using the "name" column and reset the id (autoincrement) with this new order to end up with the following
| id | name | color |
------+--------+---------
| 1 | apple | red |
| 2 | banana | yellow |
| 3 | grape | purple |
| 4 | pear | green |
QUESTION: how can I do this with MYSQL?
The cleanest way to reset the auto increment is to create another table.
MySQL provides commands such as CREATE TABLE LIKE and RENAME TABLE that are useful.
CREATE TABLE table2 LIKE table1;
INSERT INTO table2
SELECT * FROM table1 ORDER BY name;
DROP TABLE table1;
RENAME TABLE table2 TO table1;
Can I ask why you would want to do this?
If anyone modifies any of the name values or inserts new rows it will mess up your ordering scheme. Trying to store some meaning in the ordering of the PK that is already available elsewhere in the table (the name column) seems redundant and consequently a bad idea.
A much better solution is not to worry about the value of the ID column and just sort on the name column when you use the data in your app.
PS: Sorry for the non-answer type response. Normally I'd assume you had a good reason and just give an answer that directly addresses what you are trying to do, but I noticed from your other questions that you are still in the early learning stages about database design, so I wanted to help point you in the right direction instead of helping further your progress towards an ill-advised approach.
You can SELECT INTO a new table from the old table, ordering your select into as desired. Have an auto-increment ID in the new table. If needed, drop the old table and rename the new table.
Why not adding "ORDER BY name ASC" at the end of your query? My guess would be that you need the ID for some reason.
If you have a table with an autoincrement primary key (named 'id' for example), and the key is not being depended on by other tables, the way to go about this is this.
Remove the column id entirely.
alter table order by column_x, column_y;
Add the primary key column 'id' again, with autoincrement.
I did this a few times, with success and quite fast, using phpmyadmin.
Reordering a table that has a primary key as an index, is impossible. That's why u need to remove it first.
If u need to keep the 'id' column, but need to re-sort, based on other columns, u need to omit the primary key & index status of the id column & re-sort. Then you need to add a new column as primary key / index.
SELECT
RANK() Over (ORDER BY Name) As NewID
, Name
, Color
FROM Fruits
could save to a temp table then truncate then truncate the fruit table and insert, but it's probably a crappy solutions.