What is the best way to retrieve the most up-to-date status for every identifier in the table?

Here is a table for reference:

mysql> desc foo;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | NO   |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc bar;
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| foo_id          | int(11)      | NO   | MUL | NULL    |                |
| status          | varchar(255) | YES  |     | NULL    |                |
| created_at      | datetime     | NO   |     | NULL    |                |
| updated_at      | datetime     | NO   |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

The goal is to retrieve the most recent updates for foo_id and status from the bar table, considering that there may be multiple statuses associated with a single foo_id.

An attempted query looks like this:

SELECT foo_id, status
FROM bar d1
WHERE d1.updated_at =
    (SELECT MAX(d2.updated_at)
     FROM bar d2
     WHERE d1.foo_id = d2.foo_id)
GROUP BY foo_id
ORDER BY updated_at DESC;

However, an error was encountered:

Unhandled rejection SequelizeDatabaseError: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'dev.d1.status' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

How can I successfully retrieve the latest status for each foo_id from the bar table?

Answer №1

If you're looking to retrieve the id with the latest updated_at timestamp, you have a couple of options:

select foo_id, status 
from bar 
where updated_at = (
select MAX(updated_at) 
from bar 
)

You could also achieve this using a join:

select foo_id, status 
from bar 
INNER JOIN (
select MAX(updated_at)  max_date
from bar 
) t on t.max_date  = bar.updated_at 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The request from localhost:3000 to localhost:3003 could not be proxied by ReactJS

Currently, I am working on developing a Single Page Application (SPA) using create-react-app with an expressjs server as the backend. During development, my frontend test server runs on port 3000 while my backend expressjs test server runs on port 3003. T ...

Tips for troubleshooting an AWS Lambda function

Over the weekend, I spent time running node functions on AWS Lambda connected to DynamoDB. I used X-ray for debugging, creating my own annotations along the way. I'm curious if there is a more efficient method for debugging lambda functions, such as a ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

The issue arises when trying to set headers after they have already been sent in the Google Maps Places API and Express

I have been exploring the implementation of google maps places api to create a basic web application. Currently, my approach involves fetching data from the api and storing it in my mongodb database. Utilizing the google maps places npm module @google/map ...

The straightforward To-Do application fails to display tasks

Does anyone have experience building a simple To-Do application using node js, express, mongodb, and ejs? I'm encountering an issue where although I can successfully save todos to my Mongo Compass database, they do not display on the screen as expect ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

Experiencing issues with running npm commands on Plesk Onyx utilizing Node.js via SSH

After installing node.js on Plesk Onyx through the Plesk extension manager, I attempted to install the node.js driver for MongoDB using npm via SSH. However, I'm encountering issues with npm commands not being recognized. I can confirm that Node.js i ...

Guide on utilizing schema methods with mongoose and Express

I keep encountering an issue when trying to execute user.comparePassword from exports.index.post. The issues seems to be isolated to the code provided below, which includes all relevant information. While the UserSchema.pre('save') method works w ...

What is the best way to retrieve specific information from a group of data using Mongoose?

I need assistance with extracting the number from a collection that contains only a name and a number. I also want to either change the number or store it in a variable. How can I achieve this? let dataSchema = new mongoose.Schema({ name: String ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

Updating a database object in Node.js when the save event occurs in a different context

What is the most efficient method to create or update an object when saving changes to another? Let's consider a scenario where we have a Client model and emit an event upon save. clientSchema.post('save', function (client) { process.em ...

Sailsjs middleware that handles parsing of res.body data

I am a newcomer to JavaScript and recently started working with the sails framework. In my middleware, I am attempting to parse the HTTP response body to add a job to the celery queue. Despite following the documentation for skipper-, I continue to encount ...

Issue encountered with implementing Adminjs: "Unable to use import statement outside a module"

Currently diving into node express js. I am exploring the realm of writing backend code using express js and now looking to incorporate adminjs into my project. Delving into this new territory, I followed the official documentation of the adminjs express p ...

What is the purpose of NPM including an empty "etc" directory and multiple command files during installation?

After updating or installing a package in my project, I've noticed that NPM is creating an empty etc folder and multiple .cmd files (refer to image below). Additionally, my package.json file is not being updated automatically anymore. I have to manual ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

Error: The operation 'join' cannot be performed on an undefined value within Fast2sms

I am encountering issues while attempting to send SMS using fast2sms in Node.js. The error message reads as follows: TypeError: Cannot read property 'join' of undefined at Object.sendMessage (C:\Users\user\Desktop\node_module ...

What are the implications of sending a query for every individual input field alteration in a large online form?

I am creating a system for an educational institution where faculty can input scores using php and html. The layout is similar to an excel sheet, with 20 questions per student and about 60 students on each page. My dilemma is whether it's acceptable ...

Setting up Node NPM proxy authentication - what's the process?

Just diving into the world of Node and attempting to install TypeScript with this command: npm install -g typescript Encountering this error message: If you are behind a proxy, please ensure that the 'proxy' config is set correctly. I've ...