Ignore insert if exist in table in mysql? - mysql

I have 6 columns in my table:
Id | Name | Mail id | Gender | Contact Number | father name
while inserting a data into table i wanted to check condition like if Name,mailid,contact number already exists then insert should not happen else record should be inserted.
Can any one suggest how to check the condition while inserting a record.

IF NOT EXISTS (SELECT * FROM Table_Name WHERE Condition you are checking)
BEGIN
INSERT INTO ............. ---<----- Your Insert Statement.....
END

You can define an index on multiple columns, e.g.:
CREATE UNIQUE INDEX arbitrary_index_name ON table_name (Name, mailid, contactnumber);

I also faced similar situation, you can do this by adding unique constraint to your table and using 'insert ignore' statement to add data.
Create table statement:
CREATE TABLE Student (
Id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
Mailid VARCHAR(50),
Gender CHAR,
contactnumber BIGINT,
fathername VARCHAR(50),
UNIQUE(NAME,Mailid,contactnumber));
Insert Ignore statement:
INSERT IGNORE INTO student(NAME, Mailid,Gender,contactnumber,fathername) VALUES('Shekhar', 's#s.com', 'M', 987654321, 'Joshi');

Related

MYSQL insert all values from one table's column to another table based on JOIN / Relationship [duplicate]

This question already has answers here:
MySQL update table based on another tables value
(7 answers)
Closed 2 years ago.
In this case I have the following table, I need to move all values on user_sessions.session_str to users.user_string based on the user_id. How to achieve this?
**Schema (MySQL v5.7)**
CREATE TABLE users (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
user_string varchar(20)
);
INSERT INTO users (user_string) VALUES (NULL);
INSERT INTO users (user_string) VALUES (NULL);
CREATE TABLE user_sessions (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
user_id INT,
session_str varchar(20)
);
INSERT INTO user_sessions (user_id, session_str) VALUES (1,1234);
INSERT INTO user_sessions (user_id, session_str) VALUES (2,5678);
Query #1
SELECT
users.*,
user_sessions.session_str,
concat('I want ',session_str,' to be copied into users.user_string') as 'help'
FROM users
JOIN user_sessions on user_sessions.user_id = users.id;
id
user_string
session_str
help
1
1234
I want 1234 to be copied into users.user_string
2
5678
I want 5678 to be copied into users.user_string
View on DB Fiddle
Then dont insert nulls in the users table. Use insert into ... select .. as follows:
Insert into users
Select session_str from user_sessions;

How to update primary key table based on foreign key with ON DUPLICATE KEY UPDATE

I have a users table with autoincrement id as primary key, and a unique key on email. The email and name fields are from Facebook.
+----+-------+------+
| id | email | name |
+----+-------+------+
And a facebook_users table,
+--------+----------+
| userId | fbUserId |
+--------+----------+
The id is a foreign key to userId on the Facebook table. The fbUserId is guaranteed to be unique by Facebook. The reason I split these tables up is I plan to have more social logins in the future, and I'm trying to make my schema future proof.
Right now my insert update query is this
BEGIN;
INSERT IGNORE INTO users
(id,email,name)
VALUES (0,?,?);
INSERT IGNORE INTO users_facebook
(userId, fbUserId)
VALUES (LAST_INSERT_ID(), ?);
COMMIT
From what I understand, ON DUPLICATE KEY UPDATE only applies to a single row in a single table.
What I'd like to do is if one of my existing users (meaning I have their fbUserId in my database) changes their email or name on Facebook, I'd like to update the users table.
The way I'm doing it now seems.. "backward"? Because fbUserId is the "real" primary key, but I'm trying to insert into users first.
Also, any thoughts on my current query? I'm quite new to MySQL.
EDIT: I ended up moving email to facebook table and using a stored procedure.
users table is id, name ;
facebook_users table is userId, email, fbUserId;
Procedure:
CREATE PROCEDURE 'facebook_user_login'(
firstName varchar(50),
lastName varchar(50),
email varchar(50),
fbUserId bigint(8)
)
BEGIN
IF NOT EXISTS (select * from users_facebook a where a.fbUserId = fbUserId) THEN
BEGIN
INSERT INTO users values (0,'eric','guan');
INSERT INTO users_facebook values (LAST_INSERT_ID(),email, fbUserId);
END;
ELSEIF EXISTS (select * from users_facebook a where a.fbUserId = fbUserId and a.email != email ) THEN
UPDATE users_facebook set email = email;
END IF;
END

How to make SQL Server 2008 table primary key auto increment with some prefix

The given query is in mysql format. I want same query in SQL Server 2008.
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
Then you just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
And you'll have
| ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |
This may answer your question
-- create table with 'ABCD' as prefix, combining with identity column Id
CREATE TABLE dbo.Persons
(
Id int IDENTITY (1,1) NOT NULL
,PersonId AS ('ABCD' + CONVERT(varchar(20), Id)) PERSISTED NOT NULL PRIMARY KEY
,Name varchar(100)
);
GO
-- Do not specify calculated column when insert values into the table
INSERT INTO dbo.Persons (Name)
VALUES ('Person1'), ('Person2'), ('Person3');
GO
-- Display the records from the table
SELECT PersonId, Name
FROM dbo.Persons;
GO
This approach does not require to create a separate table and trigger, therefore efficient.
Hope this helps.

MySQL query returning data with detailed / duplicated information

I am working on MySQL database, and I need to select some data with procedure. So I have something like:
CREATE TABLE pet (id INT, name VARCHAR(20), own_id INT);
insert into pet values (1,"Rufus", 1);
insert into pet values (2,"Bali", 1);
insert into pet values (3,"Lolo", 2);
ref pet.own_id = own.id
CREATE TABLE own (id INT, own_name VARCHAR(20), own_color VARCHAR(20));
insert into own values (1,"Me", "Red");
insert into own values (2,"Other" ,"Green");
And now I wonder how to select / join data to get something like that (as results):
own_name own_color name
Me Red Rufus
Me Red Bali
Other Green Lolo
SELECT own_name, own_color, name
from pet
JOIN own on (pet.own_id = own.id)
;
You have only to join both tables:
Select own_name,own_color, name from own join pet on
pet.own_id = own.id
select o.own_name, o.own_color, p.name from own o, pet p
where p.own_id=o.id
It's a JOIN.
While a JOIN is a valid answer, some people find subqueries easier to read and write:
SELECT own_name, own_color, (SELECT name
FROM pet
WHERE pet.own_id = own.id) AS name
FROM own
This is basically the same as the JOIN method, but then as a subquery
I have a suggestion for your tables: own_id is a foreign key, so instead of
CREATE TABLE pet (id INT, name VARCHAR(20), own_id INT);
CREATE TABLE own (id INT, own_name VARCHAR(20), own_color VARCHAR(20));
I'd do:
CREATE TABLE own (
id INT NOT NULL AUTO_INCREMENT,
own_name VARCHAR(20) NOT NULL,
own_color VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE pet (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
own_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (own_id) REFERENCES own (id)
);
I added some other things as well.
Improvements/changes:
I assumed none of the fields should be NULL. I added NOT NULL to all the fields making it impossible for a field to have a value of NULL. (If you want some fields to be allowed to have a value of NULL just remove the NOT NULL from the CREATE TABLE statements.)
I made both id fields increment automatically. This means the insert statements can now be just insert into own (own_name, own_color) values ("Me", "Red"); and the database will automatically keep track of the ids for you.
I added primary keys so the database knows that the rows can be identified by the id fields
I added a foreign key constraint, meaning that every own_id in pet must exist in own. If you try to insert or alter a pet row in a way that breaks this constraint mysql will throw an error at you.

Read value of a column and assign to another column

MY situation is like this:
I have two tables
TEACHERS and ABSENCES each of them has a column unitid
I want to select the unitid from TEACHERS Table and insert into ABSENCES table.
EDIT:
Can this be added into this query: ("insert into absences (student_id, date) values ('".$_GET['student_id']."','".date('Y-m-d H:i:s')."')");
?
try this
INSERT INTO ABSENCES(unitid) select unitid from TEACHERS
I tried to depict your scenario as below
Create Absence Table
create table absence (absence_id int not null auto_increment primary key,
`date` datetime, `subject` varchar(20),
unit_session varchar(20), unitid int);
Insert Data to Absence Table
insert into absence(`date`, `subject`, unit_session)
values(now(),'Math','first'),(now(),'Biology','second'),(now(),'Physics','third')
Create and insert data to Teachers table
create table teachers (username varchar(10), `password` varchar(10), unitid int);
insert into teachers values('abcdsed','fgdfgfdfgd',23),
('abcdced','fgdfgrtfgd',3),('harikas','fgdfgfdfgd',23);
At this point as you can see, Absence Table don't have any value for unitid column. it's NULL.
Create a temporary table as below
create temporary table temptest(id int not null auto_increment primary key,
unit_id int);
Insert unitid from Teachers to temporary table
insert into temptest(unit_id) select unitid from teachers
Now finally, update Absence table by joining with temporary table like below
UPDATE absence a
JOIN temptest b
ON a.absence_id = b.id
SET a.unitid = b.unit_id