Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this query irreducibly complex?
    primarykey
    data
    text
    <p>I have two MySQL database tables, described below. One table holds device information, and the other is a one-to-many log about each device.</p> <pre><code>CREATE TABLE `device` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `active` INT NOT NULL DEFAULT 1, INDEX (`active`) ); CREATE TABLE `log` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `device_id` INT NOT NULL, `message` VARCHAR(255) NOT NULL, `when` DATETIME NOT NULL, INDEX (`device_id`) ); </code></pre> <p>What I want to do is grab device information along with the latest log entry for each device in a single query (if possible). So far, what I have is the following:</p> <pre><code>SELECT d.id, d.name, l.message FROM device AS d LEFT JOIN ( SELECT l1.device_id, l1.message FROM log AS l1 LEFT JOIN log AS l2 ON (l1.device_id = l2.device_id AND l1.when &lt; l2.when) WHERE l2.device_id IS NULL ) AS l ON (d.id = l.device_id) WHERE d.active = 1 GROUP BY d.id ORDER BY d.id ASC; </code></pre> <p>These queries are simplified reproductions of my actual setup, where my log table is over 100k rows (and there are actually several log tables I look at). The query does run, however very, very slowly (say, more than two minutes). I'm convinced that there is a more concise/elegant/"SQL" way to form this query to get the data I need, but I just haven't found it yet.</p> <p>Is what I want to do even possible without the ugly sub-SELECT and self-JOIN? Can I get the job done with a different strategy? Or, is the very nature of the query something that is irreducibly complex?</p> <p>Again, the application logic is such that I can "manually JOIN" the tables if this isn't going to work, but I feel like MySQL should be able to handle something like this without choking - but I'm admittedly green when it comes to this kind of complex set algebra.</p> <p><strong>EDIT:</strong> As this is a contrived example, I'd forgotten to add the index to <code>device.active</code></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.
 

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