如何使用逗号分隔值和id找到最大值到表中

时间:2016-02-09 14:59:47

标签: mysql codeigniter

我对此查询有一些问题,要在此表中找到max item_cost

DoSomething

我找到了这个功能

  OrderID     |    item_ids| item_cost
  ---------------------------------------------------------
  1             1,2,3      22,88,77
  2             2,4        83,26

但答案是完整的一行,我只需要单项的max(item_cost)

SELECT * FROM scb.invoice_out 
where FIND_IN_SET('2',item_ids) 
有同样问题的人?

1 个答案:

答案 0 :(得分:0)

您的问题的mysql解决方案可能

select
  max(SUBSTRING_INDEX(SUBSTRING_INDEX(`item_cost`, ',', numbers.n), ',', -1)) as max_id
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN invoice_out
  on CHAR_LENGTH(`item_cost`)
     -CHAR_LENGTH(REPLACE(`item_cost`, ',', ''))>=numbers.n-1
where 
    FIND_IN_SET('2',item_ids)  
order by
  OrderID, n