Mysql group_concat与in()函数

时间:2018-10-17 12:39:57

标签: mysql sql

我正在尝试在MySQL的函数中使用group concat with in function,它没有给我任何语法错误,但是我不确定它是否正常工作。

我正在尝试执行以下操作:

select
     case
         when weekday(ps.date) in (group_concat(vd.valid_days)) then ps.date
         when weekday(ps.date+1) in (group_concat(vd.valid_days)) then DATE_ADD(ps.date, INTERVAL 1 DAY)
         when weekday(ps.date+2) in (group_concat(vd.valid_days)) then DATE_ADD(ps.date, INTERVAL 2 DAY)
         when weekday(ps.date+3) in (group_concat(vd.valid_days)) then DATE_ADD(ps.date, INTERVAL 3 DAY)
         when weekday(ps.date+4) in (group_concat(vd.valid_days)) then DATE_ADD(ps.date, INTERVAL 4 DAY)
         when weekday(ps.date+5) in (group_concat(vd.valid_days)) then DATE_ADD(ps.date, INTERVAL 5 DAY)
     end as valid_date
from
    purchase_shopping  ps
    left join
    purchase_region pr on pr.id = ps.idfk_region
    left join
    valid_weeks_days vd on vd.idfk_region = pr.id
group by ps.id

我基本上需要返回的日期是有效日期,如果某天在左连接的组连接中。我不知道我的逻辑是错误的还是行不通的。 Obs:group concat函数返回类似的内容:(1,2,5),因此应该与in()函数一起使用。

带有重做的代码数据的示例:

ps.date = 2018-10-17
weekday(ps.date) = 2 
group_concat(vd.valid_days) = (1,4)
then valid_date will be 2018-10-19

2 个答案:

答案 0 :(得分:0)

也许您只是想要:

select (case when uc.id is not null then 'It has items' end)
from shopping_cart sc left join
     user_cart uc
     on uc.id = sc.idfk_cart;

答案 1 :(得分:0)

您不能在同一查询中使用group_concat的结果,因此必须使用子查询

select
     case
         when weekday(date) in valid_days then date
         when weekday(date+1) in valid_days then DATE_ADD(date, INTERVAL 1 DAY)
         when weekday(date+2) in valid_days then DATE_ADD(date, INTERVAL 2 DAY)
         when weekday(date+3) in valid_days then DATE_ADD(date, INTERVAL 3 DAY)
         when weekday(date+4) in valid_days then DATE_ADD(date, INTERVAL 4 DAY)
         when weekday(date+5) in valid_days then DATE_ADD(date, INTERVAL 5 DAY)
     end as valid_date
     from (
     select ps.date, (group_concat(vd.valid_days)) as valid_days
from
    purchase_shopping  ps
    left join
    purchase_region pr on pr.id = ps.idfk_region
    left join
    valid_weeks_days vd on vd.idfk_region = pr.id
group by ps.id
) as sub_query