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

时间:2013-12-06 11:46:34

标签: php mysql temp-tables

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

这个字符串是从php发布的,我不想将它们存储在datebase中。我想从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

2 个答案:

答案 0 :(得分:2)

您最好的方法可能是 - 使用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小提琴)。使用此功能,您可以获得最终结果:

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

-check this小提琴。但是,这可能很慢,我建议您使用应用程序层来构建所需的SQL。

答案 1 :(得分:1)

这样的事情?使用UNION生成内联视图。这可以由客户端生成。

SELECT *
FROM
(
    SELECT '18207' AS products_id, 1 as sort
    UNION
    SELECT '17631' AS products_id, 2 as sort
    UNION
    SELECT '16717' AS products_id, 3 as sort
    UNION
    SELECT '18545' AS products_id, 4 as sort
    UNION
    SELECT '9062' AS products_id, 5 as sort
) x JOIN tbl x.products_id = tbl.products_id
ORDER BY sort