Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way on MySQL to update and select the updated rows in a single statement t?

Tags:

join

select

mysql

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.

like image 203
Someone Avatar asked Nov 13 '22 14:11

Someone


1 Answers

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");
like image 121
Jürgen Steinblock Avatar answered Nov 17 '22 05:11

Jürgen Steinblock