gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:25:50 25 4
gpt4 key购买 nike

例如:
我的产品最佳排序字符串是“'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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com