Is there a way of combining these 2 MySQL statements?
I would like to run a query that adds 1 to the qa_votes
field, and then retrieves the resulting value of th开发者_StackOverflow中文版at field so I can show it on the front end.
So the code draft would be
$this->db->query("
UPDATE qa
SET qa_votes = qa_votes +1
WHERE qa_id = $question_id;
");
followed by
$query = $this->db->query("
SELECT qa_id, qa_votes
FROM qa
WHERE qa_id = $question_id;
");
Is there a way of combining these 2 into a single query?
Short answer: No.
Long Answer: Not with an out-of-the-box command. UPDATE
command does not provide that. You could, however, write a Stored Procedure that updates and then brings back the result.
Yes. You can use LAST_INSERT_ID
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID()
So you can do something like:
$this->db->query("
UPDATE qa
SET qa_votes = LAST_INSERT_ID(qa_votes +1)
WHERE qa_id = $question_id;
");
Followed by
$query = $this->db->query("SELECT LAST_INSERT_ID()");
The MySQL API that you use may have a shortcut for retrieving the last (e.g. mysql_insert_id() in PHP).
Just combine them both into a single SQL string?
$query = $this->db->query("
UPDATE qa
SET qa_votes = qa_votes +1
WHERE qa_id = $question_id;
SELECT qa_id, qa_votes
FROM qa
WHERE qa_id = $question_id;
");
精彩评论