Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Warning: Long answer. This should work, and is fairly neat, except for one step in the middle where you have to be willing to run an INSERT statement over and over until it doesn't do anything since we can't do recursive CTE things in MySQL.</p> <p>I'm going to use this data as the example instead of yours:</p> <pre><code>id Timestamp 1 1:00:00 2 1:00:03 3 1:00:06 4 1:00:10 </code></pre> <p>Here is the first query to write:</p> <pre><code>SELECT a.id as aid, b.id as bid FROM Table a JOIN Table b ON (a.Timestamp is within 3 seconds of b.Timestamp) </code></pre> <p>It returns:</p> <pre><code>aid bid 1 1 1 2 2 1 2 2 2 3 3 2 3 3 4 4 </code></pre> <p>Let's create a nice table to hold those things that won't allow duplicates:</p> <pre><code>CREATE TABLE Adjacency ( aid INT(11) , bid INT(11) , PRIMARY KEY (aid, bid) --important for later ) </code></pre> <p>Now the challenge is to find something like the <a href="http://en.wikipedia.org/wiki/Transitive_closure" rel="nofollow">transitive closure</a> of that relation. </p> <p>To do so, let's find the next level of links. by that I mean, since we have <code>1 2</code> and <code>2 3</code> in the Adjacency table, we should add <code>1 3</code>:</p> <pre><code>INSERT IGNORE INTO Adjacency(aid,bid) SELECT adj1.aid, adj2.bid FROM Adjacency adj1 JOIN Adjacency adj2 ON (adj1.bid = adj2.aid) </code></pre> <p>This is the non-elegant part: You'll need to run the above INSERT statement over and over until it doesn't add any rows to the table. I don't know if there is a neat way to do that.</p> <p>Once this is over, you will have a transitively-closed relation like this:</p> <pre><code>aid bid 1 1 1 2 1 3 --added 2 1 2 2 2 3 3 1 --added 3 2 3 3 4 4 </code></pre> <p>And now for the punchline:</p> <pre><code>SELECT aid, GROUP_CONCAT( bid ) AS Neighbors FROM Adjacency GROUP BY aid </code></pre> <p>returns:</p> <pre><code>aid Neighbors 1 1,2,3 2 1,2,3 3 1,2,3 4 4 </code></pre> <p>So</p> <pre><code>SELECT DISTINCT Neighbors FROM ( SELECT aid, GROUP_CONCAT( bid ) AS Neighbors FROM Adjacency GROUP BY aid ) Groupings </code></pre> <p>returns</p> <pre><code>Neighbors 1,2,3 4 </code></pre> <p>Whew!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload