[英]Mysql query get data if certain column is on sequence
What I want here is to retrieve pid's that have these criteria: pid
count is atleast 3 and sid
should atleast contain two numbers that are in sequence. 我要在这里检索具有以下条件的pid
: pid
计数至少为3,而sid
至少应包含按顺序排列的两个数字。 For example sid should 1 & 2, 2 & 3, 3 & 4, and so on. 例如,sid应该为1&2、2&3、3&4,依此类推。
Table sem_attendance
attendance_id sid pid
1 1 3
6 1 12
8 2 12
9 4 12
10 1 23
11 3 23
12 1 29
13 3 27
14 2 24
15 3 21
16 2 21
17 1 27
18 2 27
19 5 23
My query: 我的查询:
SELECT attendance_id, sid, sem_attendance.pid
FROM sem_attendance
INNER JOIN (
SELECT pid
FROM sem_attendance
GROUP BY pid HAVING COUNT( pid ) =3)
temp ON sem_attendance.pid = temp.pid
ORDER BY temp.pid, sem_attendance.sid
attendance_id sid pid
6 1 12
8 2 12
9 4 12
10 1 23
11 3 23
19 5 23
17 1 27
18 2 27
13 3 27
Desired output should only be pid's 12 and 27 because the sid's 1, 3 and 5 are not in sequence. 所需的输出应仅是pid的12和27,因为sid的1、3和5不在顺序中。 Is it possible to do this on mysql? 是否可以在mysql上执行此操作? If not, how about on php coding? 如果没有,在php编码上如何? Help me please. 请帮帮我。
You can split the two conditions into two separate subqueries and just pick rows with the pids that exist in both sets; 您可以将两个条件分为两个单独的子查询,并仅使用两个集中都存在的pids来选择行。
SELECT * FROM sem_attendance
WHERE pid IN ( -- at least 3 in the group
SELECT pid FROM sem_attendance
GROUP BY pid HAVING COUNT(1) >= 3
)
AND pid IN ( -- at least 2 consecutive
SELECT a.pid FROM sem_attendance a JOIN sem_attendance b
ON a.pid = b.pid AND a.sid = b.sid + 1
)
You can use the following query: 您可以使用以下查询:
SELECT attendance_id, sid, pid
FROM (
SELECT attendance_id, sid, pid,
(SELECT sid
FROM sem_attendance AS t2
WHERE t1.pid = t2.pid AND t1.attendance_id < t2.attendance_id
ORDER BY attendance_id LIMIT 1) AS next_sid
FROM sem_attendance AS t1
WHERE pid IN (SELECT pid
FROM sem_attendance
GROUP BY pid
HAVING COUNT(*) >= 3)) AS t
WHERE sid = next_sid - 1
I've made the assumption that field attendance_id
defines order in your table. 我假设字段attendance_id
定义了表中的顺序。 Consecutive table records are deduced based on this assumption. 连续表记录是基于此假设推导出来的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.