Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and Update in same query

Tags:

php

mysql

Can you select and update in the same query? I'm trying to count views to create a top blog posts by views for my sidebar.

$sql = mysql_query("SELECT * FROM articles WHERE id='$id' LIMIT 1
                    UPDATE pages SET views=views+1 WHERE ID=$id");
like image 842
Hire Logo Avatar asked Jul 11 '13 01:07

Hire Logo


People also ask

Can we use SELECT and UPDATE together in SQL?

The query structure, “UPDATE from SELECT” can be used to perform this type of data update scenario. Also, we can use alternative MERGE statements and subquery methods.

Can we use UPDATE and SELECT as a combination?

User can update the data in one table using data already stored in another table. We will use UPDATE command and SELECT command. After creating two tables, we insert values on each column of two tables after defining its data types. We have use SELECT command and UNION command to put the values of one row together.

How do I use UPDATE SELECT?

Example: SELECT FOR UPDATE in action A complete transaction that uses SELECT FOR UPDATE on that table could look like this: BEGIN; SELECT * FROM kv WHERE k = 1 FOR UPDATE; UPDATE kv SET v = v + 5 WHERE k = 1; COMMIT ; Working line by line through the statement above: The first line, BEGIN , initiates the transaction.

Can UPDATE be used in a subquery?

Like SELECT , the UPDATE statement can have a subquery in several places or clauses. In an UPDATE , the two clauses in which subqueries are used most commonly are SET and WHERE . The SET clause is where we define the new value for the column being modified by the UPDATE .


1 Answers

No, you cannot do that, but there is nothing wrong with doing two queries.

       mysql_query("UPDATE pages SET views=views+1 WHERE ID=$id");
$sql = mysql_query("SELECT * FROM articles WHERE id=$id");

Also, if id is the primary key you don't have to do LIMIT 1 here, id is unique, therefore it will always have only one result matching your condition.

like image 111
Havenard Avatar answered Oct 01 '22 07:10

Havenard