4

I have some complex SQL which consists of a series of non-query statements, that make use of temporary tables in MySql, and then a SELECT statement at the end to return the result.

e.g

DROP TABLE IF EXISTS temp_foo;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_foo AS (
    SELECT *
    FROM foo
);

SELECT * from temp_foo;

How can I run this all in the one DB call from Laravel and get the results of that last SELECT statment?

I've tried doing something like this in laravel, but it gives me a MySql syntax error, which is strange as that exact sql works ok when I run it directly in MySQl.

DB::select("

    DROP TABLE IF EXISTS temp_foo;

    CREATE TEMPORARY TABLE IF NOT EXISTS temp_foo AS (
        SELECT *
        FROM foo
    );

    SELECT * from temp_foo;

");

Any ideas on how can make this work?

0

3 Answers 3

1

You need to use DB::raw() to make your query work, for example:

DB::select(DB::raw("
    DROP TABLE IF EXISTS temp_foo;
    CREATE TEMPORARY TABLE IF NOT EXISTS temp_foo AS (
        SELECT *
        FROM foo
    );
    SELECT * from temp_foo;
"));

I think it's even possible to simply use selectRaw() but I'm not sure. Also, you can select all rows from temp_foo like this:

DB::table('temp_foo')->get();
Sign up to request clarification or add additional context in comments.

Comments

0

You need to look at DB::raw() inside the select(), but also, try using this:

DB::statement('drop table users');

Comments

0

i've done something similar in a migration where i had to create and run a stored procedure. in my up() i used something like this.

public function up() {
  $sql = <<<SQL
    DROP TABLE IF EXISTS temp_foo;

    CREATE TEMPORARY TABLE IF NOT EXISTS temp_foo AS (
      SELECT *
      FROM foo
    );

    SELECT * from temp_foo;
  SQL;

  DB::connection()->getPdo()->exec($sql);
}

you may be able to use

DB::connection()->getPdo()->exec($sql);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.