Can I join SELECT and UPDATE statement? If yes, how can I do that?
I have table which name is news.
I show news on my website. If someone read news I add 1 to hit. I do that with 2 queries:
mysql_query("SELECT * FROM news WHERE id=2 LIMIT 1");
mysql_query("UPDATE news SET hit=hit+1 WHERE id=2");
But I want to join them.
id | title | content |hit
---+-----------+-------------------+---
1 | sdfsdfdsf | dfsdffdsfds836173 |5
2 | sfsdfds | sdfsdsdfdsfdsfsd4 |9
3 | ssdfsdfds | sdfdsfs |3
Update: the OP wants to update and select the updated rows within one sql statement.
Write a stored procedure:
delimiter //;
DROP PROCEDURE IF EXISTS ReadNews//;
CREATE PROCEDURE ReadNews(IN newsId INT)
BEGIN
SELECT * FROM news WHERE id=newsId LIMIT 1;
UPDATE news SET hit=hit+1 WHERE id=newsId;
END
Usage:
CALL ReadNews(2)
Update
By the way, most mysql clients support multiple actions in a single statement. A common use for this is (Pseude C# Code)
var result = DB.Execute("INSERT INTO table (id, name) VALUES (1, 'test'); SELECT LAST_INSERT_ID()");
which will perform an Insert and Return the id of the newly created record.
You possibly could do
var result = mysql_query("UPDATE news SET hit=hit+1 WHERE id=2; SELECT * FROM news WHERE id = 2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With