Mysql autoincrement does not increment - mysql

I have this table:
mysql> desc Customers;
+------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| CustomerID | int(10) unsigned | NO | PRI | NULL | |
| Name | char(50) | NO | | NULL | |
| Address | char(100) | NO | | NULL | |
| City | char(30) | NO | | NULL | |
+------------+------------------+------+-----+---------+-------+
Now, If I want to insert sample data:
mysql> insert into Customers values(null, 'Julia Smith', '25 Oak Street', 'Airport West');
ERROR 1048 (23000): Column 'CustomerID' cannot be null
I know I cannot make the ID null, but that should be job of mysql to set it numbers and increment them. So I try to simple not specifying the id:
mysql> insert into Customers (Name, Address, City) values('Julia Smith', '25 Oak Street', 'Airport West');
Field 'CustomerID' doesn't have a default value
Now I am in trap. I cannot make id null (which is saying for mysql "increment my ID"), and I cannot omit it, becuase there is no default value. So how should I make mysql to handle ids for me in new insertions?

Primary key means that every CustomerID has to be unique. and you defined it also as NOT NULL, so that an INSERT of NULL is not permitted
instead of >| CustomerID | int(10) unsigned | NO | PRI | NULL |
Make it
CustomerID BIGINT AUTO_INCREMENT PRIMARY KEY
and you can enter your data without problem
ALTER TABLE table_name MODIFY CustomerID BIGINT AUTO_INCREMENT PRIMARY KEY

#Milan,
Delete the CustomerID var from the table. And add this field again with the following details:
Field: CustomerID,
Type: BIGINT(10),
Default: None,
Auto_increment: tick in the checkbox
Click SAVE button to save this new field in the table. Now I hopefully it will work while inserting the new record. Thanks.

Related

How to assign a JSON variable with row_to_json in PostgreSQL

I'm trying to create an annonymous function in PostgreSQL to create mock data for an application.. I would like to do a SELECT query first (to get data from a random charter) and convert all the rows into a JSON with row_to_json, then assign the result into a variable of type JSON.
I need this charter information so I can add it into bookings table.
This is not working, I think I don't know how to associate the result of the select with the variable previously created; I'm getting the error that charterData is null and I would like to know how I can achieve this..
This is the annonymous func in SQL:
BEGIN;
DO $$
DECLARE charterData JSON;
DECLARE bookingId INTEGER;
BEGIN
SELECT row_to_json(t) INTO charterData FROM (select charter_id, name from charters) t WHERE charter_id = 1;
INSERT INTO bookings (charter, yacht, email, date, guests, total, start_hour, end_hour, hotel, arrival_date) values (charterData, '{"test":1}', 'a', '12/10/1995', 8, '78', '123', '123', '123', '123')
RETURNING booking_id INTO bookingId;
END $$;
COMMIT;
Table charter:
Table "public.charters"
Column | Type | Collation | Nullable | Default
-------------+-------------------+-----------+----------+----------------------------------------------
charter_id | integer | | not null | nextval('charters_charter_id_seq'::regclass)
name | character varying | | not null |
description | character varying | | not null |
sail_hours | integer | | not null |
Indexes:
"charters_pk" PRIMARY KEY, btree (charter_id)
"name_charter" UNIQUE CONSTRAINT, btree (name)
Referenced by:
TABLE "bookings" CONSTRAINT "charters_bookings_fk" FOREIGN KEY (charter) REFERENCES charters(name) ON DELETE CASCADE
TABLE "pricing" CONSTRAINT "charters_pricing_fk" FOREIGN KEY (charter_id) REFERENCES charters(charter_id) ON DELETE CASCADE
Bookings table:
Table "public.bookings"
Column | Type | Collation | Nullable | Default
----------------+-------------------+-----------+----------+----------------------------------------------
booking_id | integer | | not null | nextval('bookings_booking_id_seq'::regclass)
charter | json | | not null |
yacht | json | | not null |
email | character varying | | not null |
date | date | | not null |
guests | integer | | not null |
total | numeric | | not null |
start_hour | character varying | | not null |
end_hour | character varying | | not null |
alcohol | character varying | | |
transportation | character varying | | |
others | character varying | | |
arrival_date | character varying | | |
hotel | character varying | | |
Indexes:
"bookings_pk" PRIMARY KEY, btree (booking_id)
"end_hour" UNIQUE CONSTRAINT, btree (end_hour)
"start_hour" UNIQUE CONSTRAINT, btree (start_hour)
Foreign-key constraints:
"charters_bookings_fk" FOREIGN KEY (charter) REFERENCES charters(name) ON DELETE CASCADE
"yachts_bookings_fk" FOREIGN KEY (yacht) REFERENCES yachts(name) ON DELETE CASCADE
Referenced by:
TABLE "bookings_extra" CONSTRAINT "bookings_extra_fk" FOREIGN KEY (booking_id) REFERENCES bookings(booking_id) ON DELETE CASCADE
Okay I have found the answer... Was kinda silly but maybe this answer will help someone
BEGIN;
DO $$
DECLARE charter JSON;
DECLARE bookingId INTEGER;
BEGIN
charter := (SELECT row_to_json(t) FROM (SELECT charter_id, name FROM charters) t WHERE charter_id = $1);
INSERT INTO bookings
(charter, yacht, email, date, passengers, total, start_hour, end_hour, hotel, arrival_date, charter_price)
values (charter, '{"test":1}', 'a', '12/10/1995', 8, '78', '123', '123', '123', '123', '132')
RETURNING booking_id INTO bookingId;
END $$;
COMMIT;

how to insert information in a table from a select statements?

I'm new working with mysql and I'm trying to insert data into a table from a different table. I've searched and I've found that I need to do something like this:
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
These are the tables' composition:
Credit_request:
Fieldname DataType
| request_id | int(10) unsigned
| customer_id | int(11)
| total_credit_value | int(11)
| Credit_request_checked | set('yes','no')
| does_apply | enum('yes','no')
| creation_time | datetime
Customers:
Fieldname DataType
| Customer_id | int(11) unsigned
| name | varchar(70)
| lastname | varchar(70)
| sex | enum('M','F')
| personal_id | varchar(16)
| phone_number | varchar(20)
| email | varchar(70)
| birthdate | date
| address | varchar(70)
| city | varchar(70)
| job | varchar(60)
| salary | int(11)
| registration_date | datetime
+-------------------+------------------
but when I try, I get a syntax error. This is my code:
INSERT INTO Credit_request(null,'Carlos',custormer_id
,default,default,
default,default,default,default)
SELECT Customer_id FROM Customers WHERE Customer_name ='Carlos';
these defaults values are supposed to be there, I've set them however, I've noticed in order to do this kind of insert I have to reference to each field name but in this case I just want one piece of information from the other table. Any help would be appreciated.
If you want to insert only secific columns, you can specify those column names and rest of the columns will be assinged default values. Your script would be:
INSERT INTO Credit_request(custormer_id)
SELECT Customer_id FROM Customers WHERE Customer_name ='Carlos';
This will add one row into Credit_request table with Carlos's customer_id in customer_id column and null in other columns.
You've got your syntax a little mixed up. The INSERT statement should declare the columns you're inserting into, the SELECT statement declares the values. For columns that have a default, you can omit them. Nullable columns always default to NULL unless otherwise stated.
INSERT INTO Credit_request(
`customer_id`,
`creation_time`
) SELECT
`Customer_id`,
NOW()
FROM `Customers`
WHERE `Customer_name` ='Carlos';

Error 1062: duplicate entry in non-primary field

I have recently started to work with MySQL for my study job and now face following problem:
My predecessor created a textmining table of the following structure:
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| TokenId | int(11) | NO | PRI | 0 | |
| Value | varchar(255) | YES | | NULL | |
| Frequency | int(11) | YES | | NULL | |
| PMID | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+-------+
In the context of restructuring, I added the following column:
+------------+--------------+------+-----+---------+-------+
| NewTokenId | int(11) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
If I now run the query:
insert into TitleToken(NewTokenId) select t.TokenId from Token as t, TitleToken as tt where t.Value = tt.Value
or even the query:
insert into TitleToken(NewTokenId) values(1);
I get following output:
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
As I said, I am relatively new to (hands-on) *SQL and it feels like a stupid mistake, but since the column NewTokenId is no primary key, not unique and even Null is YES, I thought I'd be able to insert basically anything I want.
Any hint would be appreciated... thanks in advance :)
The problem here is that you have a default value for the primary key "TokenID", if you do not insert a value for the key in your insert statement the system will automatically insert 0. However, if there is another tuple with the same value for this attribute (which is probable because the default is 0) you will get that error.
You are attempting to perform an insert into a table without providing a unique value for TokenId. By default, according to the table description, TokenId defaults to 0, you cannot have multiple identical values in that column.

Deleting equal rows in mySQL 5.7.9?

I have this table in mysql called ts1
+----------+-------------+---------------+
| position | email | date_of_birth |
+----------+-------------+---------------+
| 3 | NULL | 1987-09-03 |
| 1 | NULL | 1982-03-26 |
| 2 | Sam#gmail | 1976-10-03 |
| 2 | Sam#gmail | 1976-10-03 |
+----------+-------------+---------------+
I want to drop the equal rows using ALTER IGNORE.
I have tried
ALTER IGNORE TABLE ts1 ADD UNIQUE INDEX inx (position, email, date_of_birth);
and
ALTER IGNORE TABLE ts1 ADD UNIQUE(position, email, date_of_birth);
In both cases I get
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IGNORE TABLE ts1 ADD UNIQUE(position, email, date_of_birth)' at line 1
I'm using mySQL 5.7.9. Any suggestions?
To do it inline against the table, given just the columns you show consider the below. To do it in a new table as suggested by Strawberry, see my pastie link under comments.
create table thing
( position int not null,
email varchar(100) null,
dob date not null
);
insert thing(position,email,dob) values
(3,null,'1987-09-03'),(1,null,'1982-03-26'),
(2,'SamIAm#gmail.com','1976-10-03'),(2,'SamIAm#gmail.com','1976-10-03');
select * from thing;
+----------+------------------+------------+
| position | email | dob |
+----------+------------------+------------+
| 3 | NULL | 1987-09-03 |
| 1 | NULL | 1982-03-26 |
| 2 | SamIAm#gmail.com | 1976-10-03 |
| 2 | SamIAm#gmail.com | 1976-10-03 |
+----------+------------------+------------+
alter table thing add id int auto_increment primary key;
Delete with a join pattern, deleting subsequent dupes (that have a larger id number)
delete thing
from thing
join
( select position,email,dob,min(id) as theMin,count(*) as theCount
from thing
group by position,email,dob
having theCount>1
) xxx -- alias
on thing.position=xxx.position and thing.email=xxx.email and thing.dob=xxx.dob and thing.id>xxx.theMin
-- 1 row affected
select * from thing;
+----------+------------------+------------+----+
| position | email | dob | id |
+----------+------------------+------------+----+
| 3 | NULL | 1987-09-03 | 1 |
| 1 | NULL | 1982-03-26 | 2 |
| 2 | SamIAm#gmail.com | 1976-10-03 | 3 |
+----------+------------------+------------+----+
Add the unique index
CREATE UNIQUE INDEX `thing_my_composite` ON thing (position,email,dob); -- forbid dupes hereafter
View current table schema
show create table thing;
CREATE TABLE `thing` (
`position` int(11) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`dob` date NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `thing_my_composite` (`position`,`email`,`dob`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

Upsert - Update if exists else Insert in MySQL

I'm looking for a simple upsert (Update/Insert). The tables looks like this
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| email | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
There is no key here. The idea is to insert if email is different, else update. The Insert on duplicate key in mysql doesn't suit the purpose.
Is there an elegant way to do this?
If you cannot add a unique key on the email column, you'll check to see if the record exists first (preferably in a transaction):
SELECT id FROM mytable WHERE email = 'my#example.com' FOR UPDATE
then update the record if it exists:
UPDATE mytable SET name = 'my name' WHERE id = ?
otherwise insert it:
INSERT INTO mytable (name, email) VALUES ('my name', 'my#example.com')
what about:
REPLACE INTO table VALUES(1,'hello', 'world#example.com');