Insert and select in one row sql [duplicate] - php

This question already has answers here:
Can I use a subquery inside an INSERT statement?
(2 answers)
Closed 8 years ago.
I need to insert some values in the table.
I can do it easily using the query(from php):
mysql_query('INSERT INTO `TABLE1`(`user_id`,`value1`,`date`) VALUES("'.$user_id.'",".$value1.",".time().")');
But this time I do not have variable $user_id. I only have the username. So I need to do one more query to USERS dataase to get user_id from row where username is equal to my variable.
Is it possible not to do 2 queries? I meen INSERT and SELECT in one query?
P.S. I know that mysql_query function is depreciated. I used it here jusst for example.

Try nested subquery:
INSERT INTO `TABLE1`
(`user_id`,`value1`,`date`)
VALUES
(
(
SELECT
`user_id`
FROM
`user`
WHERE
`username` = 'your-user-name' // should be unique in order to work
),
'value1',
NOW()
);

The following query may be what you're looking for but it may be better to first get the user_id and then proceed the insert:
INSERT INTO TABLE1 (user_id, value1, date)
SELECT MAX(user_id) + 1 -- If the user_id is an numeric value...
,'user-name-here'
,NOW()
FROM TABLE1
With this query i'm getting the last user_id from the table and i increment it by 1 in order to insert the new user in the table.
Hope this will help you.

Related

Getting inserted row on if/-then-else statement

When I use an if-then-else to check if a record exists then call the last insert using $pdocon->lastInsertId() it does not return the inserted row. For example:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam')
END IF;
This (simplified) code checks to see if a record exists. If it does exist, it grabs the info. If it does not exist it inserts it. That part all works fine, the problem comes in when I try to get the inserted ID from a name the doesn't exist (returns a 0 as lastInsertId).
Is there a practical way around this?
If you want to ensure that names are not duplicated, then you should define a unique index or constraint on the column:
alter table t add unique constraint unq_my_table_first_name unique (first_name);
Then you can use the following trick to get the correct id using last_insert_id():
insert into mytable (first_name)
values ('Adam')
on duplicate key update id = last_insert_id(id);
You can then use:
select last_insert_id()
to get the last insert id regardless of whether the statement was an update or insert.
Here is a db<>fiddle.
First the question should not have PHP tag because PHP doesn't have if-then-else conditional statement that's a Visual Basic conditional statement. Nevertheless an if-else can handle this with you using the right SQL query, SQL already provides a query that solves the issue above i.e. to check for the existence of a record and that should help.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
To anyone looking in the future, another user posted the answer but then deleted it. The correct way to accomplish this is:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam');
SELECT LAST_INSERT_ID() as inserted;
END IF;

How do I delete duplicate rows in SQL? [duplicate]

This question already has answers here:
Remove duplicate rows in MySQL
(26 answers)
Closed 7 years ago.
I am trying to delete duplicate rows using SQL, whilst leaving one of the rows behind.
The table I am trying to delete duplicate rows from is called table "A" made up of:
A.AID, A.BID, A.AName, A.AType, A.APrice.
In this table I have a number of duplicate rows with all of the data exactly the same apart from the A.ID.
I am trying to create a query that will look for duplicates and then remove the duplicate making sure one of the rows are left behind. I am using phpMyAdmin and MySQL.
DELETE FROM member
WHERE id IN (SELECT *
FROM (SELECT id FROM member
GROUP BY member_id, quiz_num, question_num, answer_num HAVING (COUNT(*) > 1)
) AS A
);
use group by and count
DELETE FROM
YourTable
WHERE
AID NOT IN ( SELECT
MAX(AID)
FROM
YourTable
GROUP BY
BID ,
AName ,
AType ,
APrice );
Consider the query below, this will remove all the duplicate rows and prevents any future duplicate row.
ALTER IGNORE TABLE A ADD UNIQUE INDEX index_name (A.AID, A.BID, A.AName, A.AType, A.APrice );

How to get last inserted id from table MySQL [duplicate]

This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Last inserted id from specific table
(8 answers)
Closed 5 years ago.
I am running 1 script in php for that I need last inserted id in subscription table. By using that id I want to make notification note for that subscription.
I used:
SELECT LAST_INSERT_ID() FROM subscription
I am getting 0 instead of real last inserted value.
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
Like this :
mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$last_id = mysql_insert_id();
See this : mysql_insert_id()
LAST_INSERT_ID() returns the last id from a previous insert statement. If you want the most recently inserted record and are using Auto Increment Prime keys, you can use the code below:
SELECT MAX( id ) FROM subscription;
If you need to know what the NEXT id will be, you can get this from INFORMATION_SCHEMA
SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'test'
mysql_insert_id
This question has already been answered many times: MySQL: LAST_INSERT_ID() returns 0
You are using that function out of context. It will only work if you inserted a row immediately prior thusly:
INSERT INTO 'subscription' (name) VALUES ('John Smith');
SELECT LAST_INSERT_ID() FROM subscription
You can however select the row with the highest id, which logically would be the most recently added...
SELECT MAX( id ) FROM subscription;
The standard approach however is to simply call mysqli_insert_id or mysql_insert_id (depending on whether you are using the mysqli or mysql PHP library. I should add that the mysql library is very inadvisable to use since it is almost completely deprecated). Here's what the whole thing would ideally look like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("INSERT INTO 'subscription' (name) VALUES ('John Smith');");
printf ("New Record has id %d.\n", $mysqli->insert_id);
//Output is something like: New Record has id 999
If however you didn't insert a subscription in the same script as collecting the most recent row ID, use the 'select max' approach. This seems unlikely given that you mentioned '1 script'
Also, if your ID's are non-consecutive, or you do not have an ID field, or you have row ID's higher than the one you just added you should probably consider a 'date_added' column to determine which one was really the latest. These scenarios are rather unlikely however.
this is the better approach 2 and 3 works but MAX(id) take more time to execute.
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'dbName' AND TABLE_NAME = 'tableName';
SELECT tableName.id FROM tableName ORDER BY tableName.id DESC LIMIT 0,1;
SELECT MAX( id ) FROM tableName;
This will always give you the maximum id, which says the biggest number is the last inserted one
SELECT MAX(id) as MaximumID FROM subscription;
$last_id=mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 0 , 1" );
$row=mysql_fetch_assoc($last_id);
echo $row['id'];
Replace id by your id field name in database and table_name by your table name.

a more relible solution to LAST_INSERT_ID [duplicate]

This question already has answers here:
Easy mysql question regarding primary keys and an insert
(4 answers)
Closed 9 years ago.
so I want to link two tables with a common column "messageID". so first I insert into table 1
to get the Auto incremented id, then take that ID with LAST_INSERT_ID function and give that as the id for table 2:
$db->("INSERT INTO table_1 VALUES('','$message')");
$db->("INSERT INTO table_2 VALUES(LAST_INSERT_ID(),'$message');
but here's my concern, there might be two users running this script simultaneously, so in the few milliseconds between the two queries exicuting the LAST_INSERT_ID could have changed, so now the two id's are different. Is there any way I can prevent this possibility. I know it is not possible to insert into two tables with one query, which was my first thoughts. Any ideas much appreciated. Thank you
The LAST_INSERT_ID is local to the connection session, so it will not conflict with a different user making an insert.
You could try using scope_identity, which would be something like this:
$db->("DECLARE #LAST_ID int
INSERT INTO table_1 VALUES('','$message')"
SET #LAST_ID = SCOPE_IDENTITY()
);
$arg = ... $myARR['LAST_ID'] ... //however you want to get the LAST_ID from your query to PHP here
$db->("INSERT INTO table_2 VALUES(#arg,'$message');
or
$db->("DECLARE #LAST_ID int
INSERT INTO table_1 VALUES('','$message')"
SET #LAST_ID = SCOPE_IDENTITY()
INSERT INTO table_2 VALUES(#LAST_ID,'$message')
);
LAST_ID would be the value of the Auto incremented id

how to select last autoincrement id using php and mysql [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php/MySQL insert row then get 'id'
I have an inset command such as
insert (name) values($name);
I have id column as autoincrement. How can I get the id of the inserted record after inserting.
insert (name) values($name);
SET #lastid = LAST_INSERT_ID();
select blah_blah from table where id = #lastid;
To get that back into php, you do a normal mysql select on it like this:
select #lastid;
For mysql you can use mysql_insert_id to get the id of the last inserted row.

Categories