我有一个查询,该查询将user.id上与记录对应的两个表(用户,记录)连接起来。user_id
记录表包含多行,其中“类型”列设置了1或0值。
DB::table('users')
->join('records_dev.records', function($join) {
$join->on('users.id', '=', 'records.user_id')
->where(...);
})
->get()->toArray();
我希望它返回没有备用“类型”值但无法弄清楚如何执行此逻辑的所有用户。
让我们说一下居留地返回类型值为0 1 0的用户数组,这是正常现象,我希望它仅发出在其记录中具有0 0 1、1 1 0等的用户的信号。
任何帮助将不胜感激。
答案 0 :(得分:0)
您可以两次联接记录表,第二次联接将id移1。然后可以比较r1.type = r2.type,这意味着type列中的连续行是相同的。
此外,在这种情况下,您需要进行自定义选择。
它应该看起来像这样:
DB::table('users')
->select('users.*', 'r1*')
->join('records_dev.records r1', 'users.id', '=', 'r1.user_id')
->join('records_dev.records r2', function ($join) {
$join->on('r1.user_id', '=', '(r2.user_id - 1)')
->where('r1.type', '=', 'r2.type');
})
->get()->toArray();
或类似这样:
DB::table('users')
->select('users.*', 'r1*')
->join('records_dev.records r1', 'users.id', '=', 'r1.user_id')
->join('records_dev.records r2', 'r1.user_id', '=', '(r2.user_id - 1)')
->where('r1.type', '=', 'r2.type')
->get()->toArray();
这假定记录表的user_id列中没有空格。如果存在间隙,则可以将新列添加到记录表并对其进行排序(1、2、3,...)。然后使用该列而不是像这样的user_id(如果新列名称为seq):
$join->on('r1.seq', '=', '(r2.seq - 1)')
答案 1 :(得分:0)
我找到了这种解决方案,其中仅为第二个“记录”表创建了一个临时表。
CREATE TEMPORARY TABLE temporary_records (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id) )
SELECT user_id, id, type
FROM records ORDER BY user_id ASC, id ASC
然后,我们可以轻松找到任何连续的条目。
SELECT user_id FROM (
SELECT g1.user_id,
(g1.type LIKE g2.type) AS issue
FROM temporary_records g1
INNER JOIN temporary_records g2 ON g2.id = g1.id + 1
WHERE g1.user_id = g2.user_id ) derived_table WHERE derived_table.issue = 1
有没有更简单的方法?只是问问。