rafi
rafi

Reputation: 1543

Selecting data using dynamic SQL query

I have a table where i have a column named 'type'. I am keeping table name in that column (as the type name). I want to check the type (table name) of a row and get data from that table using an id. Is it possible to do in one single query?

Here is the structure of main table -

    CREATE TABLE `post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `column` enum('1','2','3') NOT NULL,
  `type` enum('post_image','post_video') NOT NULL,
  `title` varchar(255) CHARACTER SET utf8 NOT NULL,
  `description` text CHARACTER SET utf8 NOT NULL,
  `thumb` varchar(255) NOT NULL,
  `post_date` datetime NOT NULL,
  `views` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Here are two table for two different types in the above column -

    CREATE TABLE `post_image` (
  `post_image_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL,
  PRIMARY KEY (`post_image_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;


    CREATE TABLE `post_video` (
  `video_remote_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) NOT NULL,
  `video_type` enum('vimeo','youtube') NOT NULL,
  `video_id` int(11) NOT NULL,
  `video_url` varchar(255) NOT NULL,
  `video_title` int(11) NOT NULL,
  `video_duration` int(11) NOT NULL,
  PRIMARY KEY (`video_remote_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Upvotes: 0

Views: 111

Answers (1)

Devart
Devart

Reputation: 121902

In a single query - NO.

Try to use prepares statement. Read the name of the table into the variable, build the SELECT query string and execute it using EXECUTE command.

Upvotes: 1

Related Questions