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

时间:2018-08-03 19:16:43

标签: php mysql laravel-5

我想以逗号分隔的形式获取其他故事的案例数

我有一个如下表

表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

当我加入他们时,我想在table2中显示table_ids的数量,如下所示

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

我已经尝试过使用laravel原始查询进行如下查询

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');

请建议我该如何实现

3 个答案:

答案 0 :(得分:1)

table2是外部联接,但是where子句中的条件table2.user_id IN (...)将查询更改为内部联接。将条件从WHERE移到ON子句:

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 Fiddle

PS:WHERE 1 IN ('1,2')尝试将'1,2'转换为数字并因此匹配1。

答案 1 :(得分:0)

为此,我可能会讨厌自己,但这可能会起作用:

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

答案 2 :(得分:0)

就像评论者建议的那样,应避免在table2中添加逗号分隔的数据,因为这是一种不好的做法。

但是,话虽如此,您可以使用Laravel的查询生成器来构建您的查询,以使其更具可读性和更简洁。建立在Salman A将WHERE更改为ON的观点上,您可以这样做:

$(document).trigger($.Event("keydown", {keyCode: 74, which: 74}))