Reputation: 736
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.
Upvotes: 5
Views: 664
Reputation: 31723
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");
Upvotes: 1
Reputation: 1153
best way is to write trigger which will increment hit count on select news When SELECT * FROM news WHERE id=2 LIMIT 1 Fire trigger UPDATE news SET hit=hit+1 WHERE id=2
Upvotes: 0
Reputation: 1917
Any numeric field will do it by this (tinyint, int, float, etc).
mysql_query("UPDATE news SET hit=hit+1 WHERE id=2 ");
Hope this will help.
Upvotes: 0