php - 如何从字符串中获取临时表结果?

标签 php mysql temp-tables

例如:
我的产品最佳排序字符串是“'8207,17631,16717,18545,9062,17469,17246,17750”

这个字符串是从 php 发布的,我不想将它们存储在数据库中。我想从 mysql 查询数据并左连接一个临时表,然后按临时表的排序进行排序。

如何从字符串中获取临时表?

enter image description here

我的代码看起来像下面这样:(错误的代码)

select
    p.products_id
from
    (
        select '18207,17631,16717,18545,9062,17469,17246,17750' as products_id
    ) as p
order by p.sort

最佳答案

您最好的方法可能是 - 使用 UNION 从字符串生成行集。然而,这将需要在您的应用程序中加入您的字符串,如下所示:

$string = '18207,17631,16717,18545,9062,17469,17246,17750';
$id     = 0;
$sql    = join(' UNION ALL '.PHP_EOL, array_map(function($item) use (&$id)
{
   return 'SELECT '.(++$id).' AS sort, "'.$item.'" AS products_id';
}, explode(',', $string)));

-最终结果将是这样的:

SELECT 1 AS sort, "18207" AS products_id UNION ALL 
SELECT 2 AS sort, "17631" AS products_id UNION ALL 
SELECT 3 AS sort, "16717" AS products_id UNION ALL 
SELECT 4 AS sort, "18545" AS products_id UNION ALL 
SELECT 5 AS sort, "9062" AS products_id UNION ALL 
SELECT 6 AS sort, "17469" AS products_id UNION ALL 
SELECT 7 AS sort, "17246" AS products_id UNION ALL 
SELECT 8 AS sort, "17750" AS products_id

但是,如果您想在 SQL 中执行此操作 - 这并不容易,因为 MySQL 不支持序列 - 因此,您需要使用一些技巧来生成所需的行集。有一种生成 N 连续数字的方法:

SELECT id+1
FROM 
  (SELECT
    (two_1.id + two_2.id + two_4.id + 
    two_8.id + two_16.id) AS id
   FROM
    (SELECT 0 AS id UNION ALL SELECT 1 AS id) AS two_1
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 2 id) AS two_2
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 4 id) AS two_4
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 8 id) AS two_8
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 16 id) AS two_16
   ) AS init
LIMIT 10

-这将导致 10 数字 1..10(检查 this fiddle)。使用它,您可以获得最终结果:

SELECT 
  ELT(id+1, 18207,17631,16717,18545,9062,17469,17246,17750) AS products_id,
  id+1 AS sort
FROM 
  (SELECT
    (two_1.id + two_2.id + two_4.id + 
    two_8.id + two_16.id) AS id
   FROM
    (SELECT 0 AS id UNION ALL SELECT 1 AS id) AS two_1
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 2 id) AS two_2
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 4 id) AS two_4
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 8 id) AS two_8
    CROSS JOIN (SELECT 0 id UNION ALL SELECT 16 id) AS two_16
   ) AS init
HAVING 
  products_id IS NOT NULL

-检查this fiddle 。但是,这可能会很慢,我建议您使用您的应用程序层来构建所需的 SQL。

关于php - 如何从字符串中获取临时表结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20423091/

相关文章:

php - 如何在php中解密sha1?

php - 如何创建雅虎 smtp 服务器的套接字?

php - Zend Framework 2 PHPUnit 测试错误

mysql - MySQL中的临时表定义

php - 使用 PHP 和 mySQL 从网络搜索创建可下载的 CSV

php - Yii 使用带有 IN 条件的变量

mysql - 优化mysql慢查询

mysql - SQL 分组依据和排序依据问题

mysql - 使用临时表的问题

mysql - 在没有临时表的情况下从 MIN 小时中选择一天的 MIN 时间?