如何比较左连接上逗号分隔的ID

mnemlml8  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(269)

我想以逗号分隔的格式得到其他故事的案例数
我有一张像下面这样的table
表1

id        name
1         a
2         b
3         c
4         d
5         e
6         f

表2

id       table1_ids   user_id
1        1,2,3,4,5    1
2        1,2,3        2
3        1,2,3,4,5    1
4        1,2,3,4      2

当我加入它们时,我想在表2中显示表ID的计数,如下所示

Expected:        a-4  b-4  c-4  d-3  e-5  f-0
 Getting output:  a-4  b-4  c-4

我用laravelraw查询尝试了下面这样的查询

DB::select('select t1.name, t1.id, count(t2.id) as count
    from table1 as t1
    left join table2 as t2 on FIND_IN_SET(t1.id, t2.table1_ids)>0
    where t2.user_id in ('1,2')
    group By t1.name, t1.id');

请告诉我怎样才能做到这一点

eivgtgni

eivgtgni1#

table2 是外部连接但条件 table2.user_id IN (...) 在where子句中,将查询更改为内部联接。将条件从 WHEREON 条款:

select t1.name, t1.id, count(t2.id) as count
from table1 as t1
left join table2 as t2 on
  find_in_set(t1.id, t2.table1_ids) > 0 and
  t2.user_id in (1, 2)
group by t1.name, t1.id

sql小提琴
附言: WHERE 1 IN ('1,2') 尝试转换 '1,2' 一个数字,因此匹配1。

ruyhziif

ruyhziif2#

我可能会因此恨我自己,但这可能有用:

select
    t1.name,
    t1.id,
    count(t2.id) as count
from
    table1 as t1
left join
    table2 as t2 on
        (
            -- We need to account for all of the variations of finding t1.id in the comma-separated field
            t2.table1_ids = t1.id or -- exactly this ID
            t2.table1_ids LIKE concat( t1.id, ',%' ) or -- starts with this ID
            t2.table1_ids LIKE concat( '%,', t1.id ) or -- ends with this ID
            t2.table1_ids LIKE concat( '%,', t1.id, ',%' ) -- the ID is found between two commas
        )
where
    t2.user_id in (1,2)
group By
    t1.name, t1.id
q3aa0525

q3aa05253#

正如一位评论员所建议的,我们应该避免在表2中添加逗号分隔的数据,因为这是一种不好的做法。
不过,也就是说,您可以使用laravel的查询生成器来构建您的查询,使其更可读、更清晰。基于salman a关于更改where to on的观点,您可以这样做:

DB::table("table1 as t1")
    ->leftJoin("table2 as t2", function($join) {
        $join->on(\DB::raw("find_in_set(t1.id, t2.table1_ids) > 0 and t2.user_id in (1, 2)"), \DB::raw(""), \DB::raw(""));
    })
    ->select("t1.name", "t1.id", \DB::raw("count(t2.id) as count"))
    ->groupBy("t1.name", "t1.id")
    ->get();

相关问题