简体   繁体   中英

How to create a view in MySQL that uses the name of another databases view in PHP?

I am trying to create a view in a MySQL database that has the same name as a view in another database using this line of code in php.

mysql_query('CREATE VIEW `' . $targetDB . '`.`' . $row[0] . '` LIKE `' . $sourceDB . '`.`' . $row[0] . '`') or die(mysql_error());

However when I run my code I get this error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIKE copyinrdb . abnormal_limit_view ' at line 1

What am I doing wrong my full code is if it helps:

    <?php
set_time_limit(0);
function duplicateTables($sourceDB=NULL, $targetDB=NULL) {
    $link = mysql_connect('my_host', 'my_user', 'my_pass') or die(mysql_error()); // connect to database
                                $results = mysql_query('SHOW FULL TABLES FROM copyinrdb WHERE TABLE_TYPE= "VIEW"') or die(mysql_error());
        while($row = mysql_fetch_row($results)) {
            mysql_query('CREATE VIEW `' . $targetDB . '`.`' . $row[0] . '` LIKE `' . $sourceDB . '`.`' . $row[0] . '`') or die(mysql_error());
            mysql_query('INSERT INTO `' . $targetDB . '`.`' . $row[0] . '` SELECT * FROM `' . $sourceDB . '`.`' . $row[0] . '`') or die(mysql_error());
        }
        mysql_free_result($results);

    mysql_close($link);
} // end duplicateTables()
duplicateTables('copyinrdb', 'copytest1');
?>

CREATE VIEW db1.viewname LIKE db2.viewname simply isn't valid mysql code.

The LIKE keyword can't be used there.

The syntax is this:

CREATE
    [OR REPLACE]
    [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
    [DEFINER = { user | CURRENT_USER }]
    [SQL SECURITY { DEFINER | INVOKER }]
    VIEW view_name [(column_list)]
    AS select_statement
    [WITH [CASCADED | LOCAL] CHECK OPTION]

[ http://dev.mysql.com/doc/refman/5.7/en/create-view.html]

There is no LIKE clause in the CREATE VIEW statement in mysql, this is why you get the error message. In the loop processing the list of views get the create view statement of the view by either issuing and parsing a SHOW CREATE VIEW stetement, or query the view_definition column of information_schema.views table and prepend it with the appropriate create view syntax.

It would even be faster, if you queried the list of views directly from information_schema.views with view_definition included instead of using the show full tables command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM