I am having difficulties understand if a subquery can be used outside of the WHERE clause in an INSERT statement. I am trying to select a value already in the table and insert it into a new row, all in one statement.
My table looks like this:
section_id INT (PK)
section_name VARCHAR
section_order INT
page_id INT
For this, each "page_id" may have many sections, and they are ordered by "section_order" Example:
+------------+--------------+---------------+---------+
| section_id | section_name | section_order | page_id |
+------------+--------------+---------------+---------+
| 1 | sec-one | 1 | 1 |
| 2 | sec-two | 2 | 1 |
| 3 | sec-three | 3 | 1 |
| 4 | sec-one | 1 | 2 |
| 5 | sec-two | 2 | 2 |
+------------+--------------+---------------+---------+
As you can see, page_id 1 has three rows associated with it, where page_id 2 has two rows.
The problem I am running into is figuring out if I can get away with one SQL statement instead of two when adding a new section. I want to set the "section_order" field to the next available increment for that page_id.
What my code basically looks like now is this:
$sql = "SELECT
MAX(section_order) + 1 AS section_order
FROM
sections
WHERE
page_id='$page_id'";
$page_res = mysql_query($sql);
$page_details = mysql_fetch_array($page_res);
$section_order = $page_details['section_order'];
$sql = "INSERT INTO
sections
SET
section_name='$section_name',
section_order='$section_order',
page_id='$page_id.'";
// ...
Now this works, and works fine. However, I am wondering if it's possible to do something like this:
$sql = "INSERT INTO
sections
SET
section_name='$section_name',
section_order=(
SELECT
MAX(section_order) + 1 AS section_order
FROM
sections
WHERE
page_id='$page_id'"),
page_id='page_id'";
When trying to run this code, I get above statement, I get this error:
"You can't specify target table 'sections' for update in FROM clause"
Here's my end question: Is what I'm trying to do even possible? Or would crawling through the MySQL manual be a waste of my time? (Incidentally, I have already tried to RTFM, but got really, super confused and came here instead).
Thanks in advance.