Is it possible to auto increment column after inserting the same value and also check the duplicate value of maximum of 2 like this:
INSERT INTO info (name, date, sched) VALUES ('$name', '$date', '$sched')
// I want to auto increment for count column after inserting same date and sched
INSERT INTO appointment (date, sched) VALUES ('$date', '$sched')
Here is my table:
Somebody can help me to achieve that or suggest a better way for appointment scheduling? Thanks!
Firstly, table design like this:
create table appointment (
id int(11) unsigned not null auto_increment,
date date not null '2018-01-01',
sched varchar(20) not null defalut '',
count int(11) not null default 0,
primary key (id)
unique key `date_sched` (`date`, `sched`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Then, sql like this:
insert into appointment(date, sched, count) values ($date, $sched, $count)
on duplicate key update count = count + 1
Related
I wrote a query to put records in a table and at the same time create another. The table is created but the data is not entered. Where am I wrong? This is my code:
$sql = "INSERT INTO progetti
(data, ora, nome_progetto, anagrafica_id, preventivo, budget, eurora, scadenza, scontoaggiuntivo, ref1, tel_ref1, mail_ref1, contenuto, stato_id)
VALUES
('".$_POST["data"]."',
'".$_POST["ora"]."',
'".$_POST["nome_progetto"]."',
'".$_POST["anagrafica_id"]."',
'".$_POST["preventivo"]."',
'".$_POST["budget"]."',
'".$_POST["eurora"]."',
'".$_POST["scadenza"]."',
'".$_POST["scontoaggiuntivo"]."',
'".$_POST["ref1"]."',
'".$_POST["tel_ref1"]."',
'".$_POST["mail_ref1"]."',
'".$_POST["contenuto"]."',
'".$_POST["stato_id"]."'
)";
"CREATE TABLE $_POST[nome_progetto] (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
data date,
intervento varchar(30),
descrizione varchar(70),
ore int(2)
)";
I am trying to have the solution of the very well known INSERT IF NOT EXISTS UPDATE IF EXISTS.
But mine is not working. I don't know why, Can anyone figure it out?
Here is what I have tried yet:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude='$lathex1',longitude='$lonhex1';");
I want to update the row if the same "imei" is in there, or Insert if its not.
I have my ROW as the primary key and from phpmyadmin, I have made the imei "unique".
What am I doing wrong?
My SQL DUMP:
CREATE TABLE IF NOT EXISTS `gpsdata` (
`ROW` int(11) NOT NULL AUTO_INCREMENT,
`IMEI` varchar(255) NOT NULL,
`Latitude` varchar(255) NOT NULL,
`Longitude` varchar(255) NOT NULL,
PRIMARY KEY (`ROW`),
UNIQUE KEY `IMEI` (`IMEI`,`Latitude`,`Longitude`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
--
-- Dumping data for table `gpsdata`
--
INSERT INTO `gpsdata` (`ROW`, `IMEI`, `Latitude`, `Longitude`) VALUES
(24, '#2:359672050035420:2:*', '90.370803333333', '0'),
(30, '#2:359672050035420:2:*', '90.370803333333', '23.7584'),
(27, '#2:359672050035420:2:*', '90.370803333333', '23.75854'),
(35, '1:135790246811221:1:*', '1.0961283333333', '1.759595'),
(32, '1:135790246811221:1:*', '1.759595', '1.0961283333333');
As seen here, you need to replace the actual values in the update statement with either A| references to the alreay existing values (e.g. longitude=longitude) or B| references to the new values (e.g. longitude=VALUES(longitude), but not longitude='$lonhex1').
Your query should be rewritten:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
If you have statement based replication running on this server then there would be a problem, see the warning below:
Unsafe statement written TO the BINARY LOG USING statement FORMAT
since BINLOG_FORMAT = STATEMENT. INSERT... ON DUPLICATE KEY UPDATE
ON a TABLE WITH more THAN ONE UNIQUE KEY IS unsafe
You have to pass the column name and its value on which you have used the primary key or unique key on which you want the Duplicate Key Update.
If it gets the id(in your case ROW, latitude and longitude column on which primary and unique key is defined ) in the database, it updates it, else it inserts a new row.
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
Example:
INSERT INTO gpsdata (`row`,`imei`,`latitude`,`longitude`)
VALUES ('24','1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`='2',`Longitude`='2';
or
INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`=VALUES(`Latitude`),`Longitude`=VALUES(`Longitude);
Mysql table (migration_terms) fields are as follows
oldterm count newterm seed
I used the following create table statment.
CREATE TABLE `migration_terms`
(
`oldterm` varchar(255) DEFAULT NULL,
`count` smallint(6) DEFAULT '0',
`newterm` varchar(255) DEFAULT NULL,
`seed` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`seed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And It works, no problems there.
but then when I used the following insert into statement to populate it;
"INSERT INTO migration_terms
SELECT looseterm as oldterm,
COUNT(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
I get this error;
Column count doesn't match value count at row 1
I cannot figure out why?
If you need the table structure of the looseterms table, it was created by the following create table statement.
CREATE TABLE looseterms
(
`seed` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`looseterm` varchar(255)
)
You need to specify the columns if your select statement has fewer columns than the table
"INSERT INTO migration_terms
(oldterm,
count)
SELECT looseterm AS oldterm,
Count(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
From MySql docs on Insert Syntax
If you do not specify a list of column names for INSERT ... VALUES or
INSERT ... SELECT, values for every column in the table must be
provided by the VALUES list or the SELECT statement. If you do not
know the order of the columns in the table, use DESCRIBE tbl_name to
find out.
Your insert is adding 2 columns of data, whereas your table's definition has 4 columns
Ok, so i have a normal query that inserts to the database.
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
Now this table has also a column called "id" with auto_increment & primary key.
When it inserts it auto makes number for the column in the row. Now I want this number, and put it in column dialog, in the same row. So the inserted row have the same number/id in "id" and "dialog". How can i do that?
Not sure if this can be done in one query (or why you even want to do this), but you can use this:
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
mysql_query("UPDATE users_pm_in SET dialog = id WHERE id = '".mysql_insert_id()."');
Be sure to escape the variables properly also.
I think it would be easier to remove the autoincrement and add the id+dialog value yourself.
Check out mysql_insert_id()
You can do this, altough it's not very efficient...
Supose you have this table:
CREATE TABLE `test` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`a` INT(10) NULL DEFAULT '0',
`b` INT(10) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
You can perform the following query:
INSERT INTO test (a, b) SElECT IFNULL((MAX(id) +1),1), 200 FROM test;
Notice that "200" is some random value that will be inserted on "b" column.
I have a simple table as below.
CREATE TABLE `stats` (
`id` int(11) NOT NULL auto_increment,
`zones` varchar(100) default NULL,
`date` date default NULL,
`hits` int(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
So just storing simple hits counter per zone per day.
But I just want to increment the hits value for the same day.
I have tried the MYSQL DUPLICATE KEY UPDATE but this wont work as I may have many zones on different dates so I cant make them unique or dates.
So the only way I can think is first to do a query to see if a date exists then do a simple if() for insert/update
Is their a better way of doing such a task as there maybe be many 1000's hits per day.
Hope this makes sense :-).
And thanks if you can advise.
Declare the tuple (zone, date) as unique in your CREATE statement. This will make INSERT ... ON DUPLICATE UPDATE work as expected:
CREATE TABLE `stats` (
`id` int(11) NOT NULL auto_increment,
`zone` varchar(100) default NULL,
`date` date default NULL,
`hits` int(100) default NULL,
PRIMARY KEY (`id`),
UNIQUE (`zone`, `date`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO stats (zone, date, hits) values ('zone1', 'date1', 1) ON DUPLICATE KEY UPDATE hits = hits + 1;
$result = mysql_query("SELECT id FROM stats WHERE zone=$zone AND date=$today LIMIT 1");
if(mysql_num_rows($result)) {
$id = mysql_result($result,0);
mysql_query("UPDATE stats SET hits=hits+1 WHERE id=$id");
} else {
mysql_query("INSERT INTO stats (zone, date, hits) VALUES ($zone, $today, 1)");
}
Something like that, if I've interpreted you correctly... that's completely untested. You can figure out what the variables are.