[英]How to get result from MSSQL stored procedure with temp table in PHP Codeigniter
[英]how can i get a temp table result from a string?
例如:
我的產品最好排序字符串是''8207,17631,16717,18545,9062,17469,17246,17750“
這個字符串是從php發布的,我不想將它們存儲在datebase中。 我想從mysql查詢數據並離開加入臨時表然后按臨時表的排序。
如何從字符串中獲取此臨時表?
我的代碼似乎就像下面那樣:(錯誤的代碼)
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
(檢查這個小提琴)。 使用此功能,您可以獲得最終結果:
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
- 檢查這個小提琴。 但是,這可能很慢,我建議您使用應用程序層來構建所需的SQL。
這樣的事情? 使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.