I have a mysql query doubt.
I have a student table email is the column name, before inserting new student i need to make sure same email can't be inserted.How can i right insert and check in one query(using sub query).
Please help me to find a solution
Thanks
The right way is to enforce it with unique constraint, but if you want to do in insert query, you can try something like
insert into student(field1, field2, email)
select 'value1', 'value2','test#test.com' from dual
where not exists (select null from student where email='test#test.com')
Note :if you use an engine that supports transactions, you may still end up having duplicate)
Related
and thanks in advance. I have a table called users which contains an id. I would like to collect the ids only from that table and run and insert using those ids as one of the arguments. I am new to SQL and having some trouble finding help or a solution.
Here is the statement to get the ids
SELECT id FROM public.usersWith the ids that are returned I would like to run an insert or update resembling insert into public.history (user_id, password, change_time) values (<ids from prev SELECT>, 'password', now());
Can I generate a loop? Could someone point me in the right direction using purely sql, I know this can be achieved in php but I'd like to include this in an db init with SQL only.
You can do it with INSERT INTO ... SELECT:
INSERT INTO public.history (user_id, password, change_time)
SELECT id, 'password', now()
FROM public.users
I need to read data from one table and insert into multiple rows in another table in a MySQL database.
Table 1 looks like:
ID, name, e-mail, phone, city, ..., ....
In Table 2 I need to insert data like:
(row1) ID, "name", name
(row2) ID, "e-mail, e-mail
(row3) ID, "phone", phone
...
...
Table 1 has about 3000 rows
I guess I need to use some kind of foreach or do..while but can't find anything that works.
Can anyone give me a clue how to do this?
If I understand your question correctly, you are wanting to do a query on table1 that returns multiple rows, and then insert those into table2 in a single loop. That's the INSERT INTO SELECT statement:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1;
It can be modified to grab specific results as well:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1
WHERE name = 'target person';
More information can be found at http://dev.mysql.com/doc/refman/5.7/en/insert-select.html and http://www.w3schools.com/sql/sql_insert_into_select.asp.
EDIT:
Based on your comment, it sounds like you're trying to do this:
SQL split values to multiple rows.
I can't think of a situation where you'd actually want to do that, as you can access all of the data in your existing table as is, and it seems to be bad practice to split data in the way you're requesting. However, the solutions in the above thread should be applicable to what you're trying to do.
Ultimately, you may want to look at how you're actually retrieving the data. Modifying that code would be a better idea :)
Just do a simple INSERT INTO SELECT with group by "id". Here for each id it will insert a new record.
INSERT INTO table2 (name, email, phone)
SELECT name, email, phone FROM table1 GROUP BY id;
Just an update on how I did do this. Since I don't have full access to the database server, I can just add/remove data and create new tables, it was not possible to create a function as suggested in the link provided in the answer.
Instead of trying to loop through the data I did an INSERT for each new row like:
INSERT INTO table2 (id,col2,col3)
SELECT id,'name',name FROM table1;
INSERT INTO table2 (id,col2,col3)
SELECT id,'email',email FROM table1;
Thanks again for the help provided.
I am having an issue using Last_Insert_Id in a VB.NET TableAdapter Insert query wired to a MySQL database. I've read through numerous posts on this site and others regarding Last_Insert_ID and Scope_Identity, etc. None of which have worked in my case.
A little background, I have two tables, one holds login information (Auto-generated ID, username, password). Another table has a foreign key relationship on the ID values and contains ID, first name, last name, city, state.
In my TableAdapter I have an Insert query that inserts values into the first table and is supposed to return the ID value so that an Insert can be done on table 2.
Here is my Query:
INSERT INTO user_logins (user_login, user_pass)
VALUES (#p1, #p2)
I wanted to add Last_Insert_Id to make the query
INSERT INTO user_logins (user_login, user_pass)
VALUES (#p1, #p2)
SELECT LAST_INSERT_ID();
However that will only return a value of 1, regardless of what the ID is. If I open the Query Builder I get a message that states "Unable to parse query text". I tried changing the ExecuteMode to Scalar, but that didn't help either.
The Insert part is working perfectly, if I could only obtain the ID value back after insert.
Does anyone know anything I might try, or alternatively, some better way to achieve this?
Thanks!
You don't even need to use SELECT LAST_INSERT_ID();
just INSERT INTO user_logins (user_login, user_pass) VALUES (#p1, #p2) is OK
To retrieve last insert Id you can use two ways
Dim t As Integer
cmd.ExecuteNonQuery()
t = (Int32) cmd.LastInsertedId
OR
t = Convert.ToInt32(cmd.ExecuteScalar())
I would like to insert a record into a table if a record doesnt exist already exist with that domain name. The following SQL should achieve this but is getting an error.
The reason I want to do the update first is because I am doing multiple updates later in my code and need the record in my table first before doing all of the updates.
Why am I getting an error on this mySQL query?
insert into domain (name)
values ('domain.com.au')
WHERE NOT EXISTS
(
select name
from domain
where name = 'domain.com.au'
);
Both queries when split work fine but when together do not.
Let your database handle it for you. Use a unique index on name and your INSERT will fail if you try to insert a duplicate.
CREATE UNIQUE INDEX idx_name ON domain (name)
You cannot combine WHERE with INSERT clause. Use REPLACE INTO instead.
What error are you getting?
My guess would be the that the select inside the 'where not exists' is not allowed.
I want to insert new user into users table and make sure that user's nick and email are not already in the table (InnoDB).
Here is my logic:
if (SELECT COUNT(*) FROM users WHERE nick = :nick) > 0:
return "name exists";
if (SELECT COUNT(*) FROM users WHERE email = :email) > 0:
return "email exists";
# OK to insert? Or something bad can happen here?
INSERT INTO users (nick, email) VALUES (:nick, :email)
But now I'm not sure if this is the right way. Suppose that between SELECT and INSERT query some other, concurrent connection creates new record with same nick or email (is this even possible?). Then INSERT will throw an exception and I'm unable to provide any feedback to the front end (beside simple "error occurred, try again).
Another idea is to use INSERT IGNORE and then check LAST_INSERT_ID(), but can I always be sure LAST_INSERT_ID()==0 when insertion is skipped?
Is there any better way to handle this?
Why don't you use a UNIQUE INDEX? Just insert the new value and let the query fail when the unique constraint is violated. A bit of errorhandling will do the trick.
The UNIQUE contraint will also solve your problem with concurrent users.
INSERT INTO users (nick, email)
SELECT :nick, :email
FROM Dual
WHERE NOT EXISTS (
SELECT 1
FROM users
WHERE nick = :nick OR email = :email
)
most MySql connectors out there have a way to get the rows affected, or you can SELECT ROW_COUNT().
Good question.
unfortinately mysql doesnt support something like "insert into if not exists".
there are several ugly solutions.
mostly the best is to handle it in your application. select before, see if you get anything, only insert if you dont get anything.
then you can put a unique key on the fields to ensure that the database keeps consistent.
you can also directly insert and rely on the unique keys. you will get an error which you have to deal with in your application. you CAN distinguish between the errors so you can display the proper message. duplicate key will be a 1062 if i remember that correclty.
however there ARE means to accomplish this with other teqniques.
one that i know of is called a mutex table.
it works so that you create a second table "mutex" which has the syme key fields as your working table which i now call "table".
then you can do something like:
isnert into table (field1,field2) select ("input1","input2") from mutex left outer join table on(mutex.field1 = table.field1 AND mutex.field2 = table.field2) where mutex.field1 != "input1" AND mutex.field2 != "field2"
i did not test this and i hope i remember the tequnique correctly, better look it up!
it is also possible to advance this to mre flexibility so you can for example only allow a desired number of duplicates in one table.
but this does not ensure data consistency as the data table is accessible as well, so i would really recommend the first method: rely on key constraints where possible, and deal with the error number in your app, if that is not possible, deal with it in your application.
Based on the following link click here
mysql> LOCK TABLE t WRITE, t AS t1 READ;
mysql> INSERT INTO t SELECT * FROM t;
ERROR 1100: Table 't' was not locked with LOCK TABLES
mysql> INSERT INTO t SELECT * FROM t AS t1;
LOCK TABLE users WRITE, users AS t1 READ;
INSERT INTO users (nick, email)
SELECT :nick, :email
FROM Dual
WHERE NOT EXISTS (
SELECT *
FROM users AS t1
WHERE nick = :nick OR email = :email
)
UNLOCK TABLES;