Jump to content

Recommended Posts

I have following piece of code below, and I would like to be able to express it pure SQL, something that could go into a .sql file :

$request_string='SELECT topic_forum_id FROM topic_table WHERE topic_id= 2014';
$query=database->prepare($request_string);
$query->execute();
$data=$query->fetch();
$query->closeCursor();
$forum=$data['topic_forum_id'];

$request_string='INSERT INTO post_table
(post_topic,post_forum) VALUES (2014,:forum)';
$query=database->prepare($request_string);
$query->bindValue(':forum',$forum,PDO::PARAM_INT);
$query->execute();
$data=$query->fetch();
$query->closeCursor();

 

Is it possible ?

 

If that hard-code "2014" never needs to change

INSERT INTO post_table (post_topic, post_forum) 
    SELECT 2014, topic_forum_id 
    FROM topic_table
    WHERE topic_id= 2014;

This sort of code is completely new to me. I understand SELECT acts a subquery in it ? Where is that construct explained in the MySQL manual ?

acts?  What's a 'acts'?

 

act:

verb
  • behave
  • perform
  • operate
  • function

 

@roparzhhemon237,

 

It isn't a subquery, it is part of the INSERT...SELECT syntax, as Ch0cu3r's link shows

Edited by Barand

An insert select statement is explained here

 

Basically the rows returned by the select statement will used as the values to insert into the table.

 

Thank you for your helpful answer.

Can I use this construct with UPDATE also ? E.g, can I write something like

UPDATE post_table SET post_forum_id=(SELECT topic_forum_id FROM table_topic WHERE topic_id=2014) WHERE post_id=237;
 

This looks like a real subquery this time.

Probably. Let us know.

 

Or, you could

UPDATE post
    JOIN topic ON topic_id = 2014
SET post_forum_id = topic_forum_id
WHERE post_id = 237;
Edited by Barand
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.