Php 如何比较左连接上逗号分隔的ID
我想以逗号分隔的格式得到其他故事的案例数 我有一张像下面这样的桌子Php 如何比较左连接上逗号分隔的ID,php,mysql,laravel-5,Php,Mysql,Laravel 5,我想以逗号分隔的格式得到其他故事的案例数 我有一张像下面这样的桌子 Expected: a-4 b-4 c-4 d-3 e-5 f-0 Getting output: a-4 b-4 c-4 表1 id name 1 a 2 b 3 c 4 d 5 e 6 f 表2 id table1_ids user_id 1 1,2
Expected: a-4 b-4 c-4 d-3 e-5 f-0
Getting output: a-4 b-4 c-4
表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
我尝试过使用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');
请建议我如何做到这一点我可能会因此恨自己,但这可能奏效:
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
table2是外部联接的,但条件table2.user_id在。。。在where子句中,将查询更改为内部联接。将条件从WHERE移至ON子句:
注:“1,2”中的1试图将“1,2”转换为一个数字,从而与1匹配。正如评论员建议的那样,应避免在表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();
这就是为什么有一个叫做数据库规范化的东西:。看一看1NF。以这种方式加入似乎有点奇怪,但我注意到的第一个问题是t2。在“1,2”中的user_id将始终为false,因为没有user_id='1,2',您需要删除引号。但这让我想知道你是怎么得到这个查询的结果的。。。条件将其转换为不匹配的内部联接。另一方面,那些1,2左右的单引号正在停止和启动您的php字符串,所以谁知道真正的结果是什么呢。像那样用逗号分隔的数据非常糟糕。你不必这么做,但这样做会让你的生活变得艰难。