简体   繁体   English

如何从关联数组中显示 SQL 虚拟/临时表

[英]How to show a SQL virtual/temporary table from associative array

I need a simple SQL query to show a virtual/temporary table without creating it in the database.我需要一个简单的 SQL 查询来显示虚拟/临时表而不在数据库中创建它。

I'm using PHP to create that query string with the data.我正在使用 PHP 使用数据创建该查询字符串。

My current PHP code is,我当前的 PHP 代码是,

$array = [
    ['id' => 1, 'name' => 'one'],
    ['id' => 2, 'name' => 'two'],
    ['id' => 3, 'name' => 'three']
];

$subQuery = "SELECT {$array[0]['id']} AS col1, '{$array[0]['name']}' AS col2";

for ($i=1; $i < count($array); $i++) {
    $subQuery .= " UNION ALL SELECT {$array[$i]['id']}, '{$array[$i]['name']}'";
}

$sql = "WITH cte AS
(
  {$subQuery}
)
SELECT col1, col2 FROM cte;";

echo $sql;

Its output is,它的 output 是,

WITH cte AS
(
  SELECT 1 AS col1, 'one' AS col2 UNION ALL SELECT 2, 'two' UNION ALL SELECT 3, 'three'
)
SELECT col1, col2 FROM cte;

// Output table from the SQL
col1    col2
1       one
2       two
3       three

I got the idea for this query from here .我从这里得到了这个查询的想法。

But the problem with this query is that, if I have 100 data in the $array, the UNION ALL part is getting included 100 times in the SQL.但是这个查询的问题是,如果我在 $array 中有 100 个数据,则UNION ALL部分将被包含在 SQL 中 100 次。 I feel like it is not a better SQL because it's like UNION 100 tables at the same time.我觉得它不是一个更好的 SQL 因为它同时就像 UNION 100 表。

I also can create a temporary table ( CREATE TEMPORARY TABLE table_name ) instead of this WITH clause, but it is not a single query because I need another query to INSERT the records to that temporary table.我还可以创建一个临时表 ( CREATE TEMPORARY TABLE table_name ) 而不是这个WITH子句,但这不是一个查询,因为我需要另一个查询来将记录插入到该临时表中。

Can someone please help me to simplify this query in a better way?有人可以帮我以更好的方式简化此查询吗?

When you use MySQL 8 you can use json_table expression like:当您使用 MySQL 8 时,您可以使用json_table表达式,如:

<?php
$array = [
    ['id' => 1, 'name' => 'one'],
    ['id' => 2, 'name' => 'two'],
    ['id' => 3, 'name' => 'three']
];

$data = json_encode($array);

$sql = "SELECT tbl.* 
FROM JSON_TABLE(
        '{\"data\":$data}',
        '$.data[*]' COLUMNS (
                id VARCHAR(40)  PATH '$.id',
                name VARCHAR(100) PATH '$.name')
     ) tbl";

echo $sql;

PHP online editor PHP 在线编辑器

The result of above query in MySQL 8.0 is:在 MySQL 8.0 中上述查询的结果是:

+====+=======+
| id | name  |
+====+=======+
| 1  | one   |
+----+-------+
| 2  | two   |
+----+-------+
| 3  | three |
+----+-------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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