I have a table which an auto-increment ID column. I want my database to automatically change the ID value so there is always an ID value of 1.
For example:
ID Firstname Lastname
1 John Smith
2 Charlie Jacobs
3 Jason young
I want it so that if I delete row ID 1 then row ID 2 changes to ID 1 and row ID 3 changes to ID 2. Like this:
ID Firstname Lastname
1 Charlie Jacobs
2 Jason young
I want to be able to then add names after which would carry on from ID 3. Preferably I was wondering if there was a setting in SQL that can do this automatically. If this isn't possible then a PHP script would be the second best thing.
That is not a right thing to do. Why do you want to do that? This would mess up your primary key values. So don't do it. Coming to the solution
If you are displaying this inside a form, just generate a row number for each row in your select statement. It will not have any gaps in between. MYSQL Generating Row Numbers
SELECT #row_number:=#row_number+1 AS row_number,db_names FROM mysql_testing,
(SELECT #row_number:=0) AS t
ORDER BY db_names;
Related
let me say that I have a table in my phpmyadmin that looks like this:
id | name
1 | John
2 | Dave
5 | Tiffany
As U can see by id - i've deleted 2 records between 'Dave' and 'Tiffany'.
My question:
Is there a way to 'reset' or repopulate the id so that the 'Tiffany' record would have id=3 and so on ?
The only way to start counting id again I've found is a 'TRUNCATE' but it deletes all my records which I dont want
I do this sometimes when I create a new table and want to get 'clean' ids. If there is no reference to / connection with other table, you can do:
SET #var:=0;
UPDATE `table` SET `id`=(#var:=#var+1);
ALTER TABLE `table` AUTO_INCREMENT = 1;
Do not do this for ids already used in other tables!
I have a table with an value that I would like to be updated periodically with a cron job. However, I need to update the value by replacing it with a value from a different table. The issue is that I would like the replacement value to be chosen randomly.
For example, Table 1 has
ID Email
=================
1 bobatumail
Table 2 has:
ID Email
================
1 bobatumail
2 joeatumail
3 peteatumail
4 biffatumail
5 wilneratumail
6 wilsonatumail
I would like the query to replace bobatumail in Table 1 with any of the other values in Table 2 as long as it is random. It could even be the same value as in Table 1.
Any idea how to do this?
In MySQL you could use the REPLACE statement:
REPLACE INTO table1 (ID, Email)
SELECT 1, table2.Email FROM table2 ORDER BY RAND() LIMIT 1;
The "1" in the second line represents the id of the entry while the second part returns a random value out of table2. Yes, there are solutions using the UPDATE statement (JOIN and ANSI) but its always tricky and you usually have to turn off safe update mode.
http://dev.mysql.com/doc/refman/5.5/en/mysql-command-options.html#option_mysql_safe-updates
Please note that REPLACE first deletes the old entry and then reinserts the new one.
http://dev.mysql.com/doc/refman/5.5/en/replace.html
How can I SELECT the last row in a MySQL table?
I'm INSERTING data and I need to retrieve a column value from the previous row.
(I'm using PHP by the way.)
the table1 something like this
table1
******************
cate_id | task_id | start_date | end_date | line |
1 2 30/04/2012 26/06/2012 text
3 1 26/06/2012 27/06/2012 text
2 1 27/06/2012 01/01/9999 text
There'sNO an auto_incrementin that table.
And my case is to update the existing last row in table and then insert a new one.
You've edited question so, here's update
SELECT MAX(cate_id) AS last_cate_id FROM table;
or you can get next ID by:
SELECT MAX(cate_id)+1 AS next_cate_id FROM table;
Without transactions this is very vulnerable for inserting same cate_id!
If you cant use them, for example because of MyISAM, you could insert with select.
INSERT INTO table
(cate_id, task_id ..)
VALUES
( (SELECT MAX(cate_id)+1 AS next_cate_id FROM table), 1 )
if you don't have order by you wont be able to get the "LAST" value or the first, because the order will not be the same (necessarily), if you don't have auto increment how can you know which one is the first or the last?, if you are working with date or auto increment you will be able to get that, however, lets say that you have a order by 'column1' you can do something like:
select * from table1 order by `column1` desc limit 1
I have a MySQL query that looks like this:
UPDATE `Table` SET `Column` =
CASE
WHEN `Option Id` = '1' THEN 'Apple'
WHEN `Option Id` = '2' THEN 'Banana'
WHEN `Option Id` = '3' THEN 'Q-Tip'
END
An my table currently looks like this:
Option Id | Column
1 | x
2 | x
I'd like it to result in:
Option Id | Column
1 | Apple
2 | Banana
3 | Q-Tip
But it doesn't insert the Q-Tip row. I've looked up and read a bit about INSERT ON DUPLICATE KEY UPDATE and REPLACE, but I can't find a way to get those to work with this multiple row update using CASE. Do I have to write a separate query for each row to get this to work, or is there a nice way to do this in MySQL?
Option Id is not a Key itself, but it is part of the Primary Key.
EDIT Some more info:
I'm programming in PHP, and essentially I'm storing an array for the user. Option Id is the key, and Column is the value. So for simplicities sake, my table could look like:
User Id | Option Id | Value
10 | 1 | Apple
10 | 2 | Shoe
11 | 1 | Czar
...
That user can easily update the elements in the array and add new ones, then POST the array to the server, in which case I'd like to store it in the table. My query above updates any array elements that they've edited, but it doesn't insert the new ones. I'm wondering if there is a query that can take my array from POST and insert it into the table without me having to write a loop and have a query for every array element.
This should work, if Option_Id is a primary key:
REPLACE INTO `Table` (`Option_Id`, `Column`) VALUES
(1, 'Apple'),
(2, 'Banana'),
(3, 'Q-Tip');
The statement means: Insert the given rows or replace the values, if the PK is already existing.
Of course it does not insert. As there is no such value, it cannot get updated.
I suppose you are normalizing a database by putting in the values already present and now want to add the required mapping for every valid value.
So it would be better to start from scratch and just do INSERTs.
You could always query the database for entries and then choose update or insert based on yor results
I see no point in such updating.
Why don't you have a separate table with option ids and corresponding values, leaving only option ids linked to user ids in this one?
For example, I have a table which looks like this :
id | name
1 | Mike
2 | Adam
3 | John
4 | Sarah
...
Now, when I execute query select * from table order by id desc it will output something like this:
4 | Sarah
3 | John
2 | Adam
1 | Mike
Now what do I do if I want to move John's row up or down, or move Adam's row up or down ( with a MySQL query ( I need basic one, just to know from where to start )).
My solution :
First of all, I created another column named orderID which has the same value as id.
Here is an example which moves up a user:
$query = "
SELECT (
SELECT orderID
FROM test WHERE id = 'user id that i want to move up'
) AS user_order,
(
SELECT orderID
FROM test WHERE orderID > user_order
ORDER BY orderID
LIMIT 0,1
) AS nextUser_order
";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
$query = "
UPDATE test SET orderID = IF(orderID='{$data[nextUser_order]}',
'{$data[user_order]}', '{$data[nextUser_order]}')
WHERE orderID IN ('{$data[nextUser_order]}', '{$data[user_order]}');
";
$result = mysql_query($query);
Is there a better way to do that?
You have to switch IDs, or to order it by another column. That's the only way.
Changing the id is not what you want to do. You never want to mess with your primary key especially because later down the road it would be easier (and take up much less space, one is an int the other a varchar) to reference your users using their id rather than their name from other tables, it is nice to have a field that you know will never change.
Make another field such as order as a floating point number.
When you move foo between bar and foobar, set foo's order to the average of bar and foobar's order.
You can put arbitrary values into an order by clause in a query, but none will work easily for a simple "move up/down a row" type things. You can force certain values to sort first or last, but not "put this value after that value, but let that value go into its natural place". You'd need to have an extra field to specify sorting order.
SQL tables aren't inherently ordered - they effectively behave like a "bag of rows". If you want the results in a specific order, you will need to sort them (using ORDER BY ...) when you pull them out of the bag -- otherwise, the SQL server will return them in whatever order it feels is easiest. (In this case, they're coming out in the reverse order you inserted them, but that's not guaranteed at all.)
You should def be using another column which holds the order of the display. id is just a unique identifier. On a relational database moving up and down rows might result in a lot of queries because of the updates on the related tables so I stick with the idea of defining a special row for this purpose.