Retrieve the row based on the user_id and also include any rows that have the same event_id as that entry

I have a table with the following structure:

 _______________________________
| event_id | user_id | username |
|-------------------------------|
|    30    |    1    |   user1  |
|    30    |    2    |   user2  |
|    30    |    3    |   user3  |
|    31    |    1    |   user1  |
|    31    |    4    |   user4  |
|    31    |    7    |   user5  |
|    32    |    3    |   user1  |
|    32    |    4    |   user4  |
|    32    |    5    |   user5  |
|_______________________________|

I initially thought about storing users as JSON:

 _______________________________________________________
| event_id |                   users                    |
|-------------------------------------------------------|
|    30    | [{"user_id": 1, "username": "user1"}, ...] |
|    31    | [{"user_id": 1, "username": "user1"}, ...] |
|    32    | [{"user_id": 5, "username": "user5"}, ...] |
|_______________________________________________________|

However, I anticipate that this approach would negatively impact performance when attempting to search for an event based on a specific JSON value.

I am looking for a way to query and retrieve all events where a username is present, returning all rows with matching event_id. Is it possible to accomplish this using a single query in order to minimize server load, or would it be better to use a nested select statement?

Answer №1

I need the ability to search for occurrences of a specific username within events and retrieve all rows that share the same event_id.

A possible solution is to utilize the "exists" clause along with a correlated subquery:

SELECT t.*
FROM mytable t
WHERE EXISTS (
    SELECT 1 FROM mytable t1 WHERE t1.event_id = t.event_id AND t1.username = ?
)

To enhance performance, it would be beneficial to create an index on the columns (username, event_id).

The question mark denotes the placeholder for the targeted username.

Personally, I would advise against storing data as JSON in this scenario since it would add unnecessary complexity to queries without providing significant benefits. The current tabular structure effectively accommodates the consistent nature of your stored information.

Answer №2

Discover the power of group_concat with this amazing query. You can see it in action on our interactive db-fiddle.

select
    event_id,
    concat('[', group_concat(concat('{"user_id":', user_id, ', "username":"',username,'"}')), ']') as users   
from yourTable
group by
    event_id

The above query will produce the following output:

| event_id | users                                                                                                       |
| -------- | ----------------------------------------------------------------------------------------------------------- |
| 30       | [{"user_id":1, "username":"user1"},{"user_id":2, "username":"user2"},{"user_id":3, "username":"user3"}] |
| 31       | [{"user_id":1, "username":"user1"},{"user_id":4, "username":"user4"},{"user_id":7, "username":"user5"}] |
| 32       | [{"user_id":3, "username":"user1"},{"user_id":4, "username":"user4"},{"user_id":5, "username":"user5"}] |

Answer №3

Based on your statement that a query is utilized to generate the table, here is a possible solution:

To obtain the desired outcome, you can execute the following SQL statement:

SELECT e.*, u.user_name
FROM events AS e 
JOIN users AS u
ON e.user_id = u.user_id
WHERE EXISTS (
    SELECT 1
    FROM events AS e2
    WHERE e2.event_id = e.event_id AND
    e2.user_id = :user_id -- choose the appropriate value for user_id
);

If this aligns with your query, it would be beneficial to create an index on events(event_id, user_id) in order to enhance performance.

Answer №4

After careful consideration, I opted for a nested select query that retrieves the event_id. Initially, I disregarded this approach under the assumption that enabling the multiple statement queries option of node-mysql was necessary. However, it became apparent that this was not the case.

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 Angular framework is unable to locate a differ that supports the object '[object Object]' which is of type 'object'

In my Angular project, I am calling an API and receiving the following JSON data: { "id": 16, "poste": "ameur taboui", "desciption": "f", "service": "f", ...

Is there a way to display the entire stack trace in Mocha when testing Promises and an error occurs?

Imagine I have a small specification like this: describe("feature", () => { it("does something", () => { return myPromiseBasedFn().then(result => { expect(result).to.eql(1); }); }); }); At the moment, when the promise is reject ...

What is the best way to add up the attributes of objects within an array and save the total to the main

I have a collection of objects, illustrated here: var obj = { "ABC" : { "name" : "ABC", "budget" : 0, "expense" : 0, "ledgers" : [{ "Actual1920": 10, "Budget1920": 20, }, { "Actual1920": 10, ...

Retrieving a specific value from a JSON object

I am currently working with a JSON object and I have it displayed in the console. Here is how it looks: [ { "name":"A", "value":"..." }, { "name":"B", "value":"..." }, { "name":"c", "value":"..." ...

Sending data from JQuery to a PHP file

My JQGrid is set up to display bookings with a double click event: ondblClickRow: function(rowid) { rowData = $("#bookings").getRowData(rowid); var brData = rowData['bookref']; getGridRow(brData); }, The data then gets passed to the ...

Assign a specific index value from a PHP array to a JavaScript variable

Having a large PHP array with 649 indexes, I am looking to assign a specific index value to a JavaScript variable based on another variable. Is there a way to achieve this without loading the entire PHP array onto the client side for speed and security rea ...

The npm outdated command seems to ignore the caret notation specified in the package.json file

When looking at a package.json file that contains the following: "devDependencies": { "grunt": "^0.4.5", "grunt-concurrent": "^1.0.0", "grunt-contrib-jshint": "^0.10.0", "grunt-contrib-watch": "^0.6.1", "grunt-dev-update": "^1.1.0", ...

Desktop Application Encounters Surprising 'List Index Out of Range' Problem Without Any Previous Changes Made

After flawlessly reading the same 2 unchanged JSON files for the past 4 years, my Python desktop app suddenly encountered a perplexing 'List index out of range' error. Despite several attempts at debugging, I am struggling to pinpoint the exact c ...

Tips for Resolving This Issue: Dealing with Cross-Origin Read Blocking (CORB) Preventing Cross-Origin Response

Caution: jquery-1.9.1.js:8526 The Cross-Origin Read Blocking (CORB) feature has blocked a cross-origin response from with MIME type application/json. For more details, refer to . My Code snippet is as follows: <!DOCTYPE html> <html> <hea ...

Having trouble sending `req.params` through http-proxy-middleware in a NodeJS/Express application?

I'm still getting the hang of Node, and I've run into an issue with passing request parameters using http-proxy-middleware. Every time I try, I keep getting a 404 error. This is my express listener setup: app.put("/api/markets/:id",()=>{..c ...

Having trouble connecting through PDO, but no issues when using the command line

UPDATE: I tried connecting to the command line using the following command mysql -u root -proot -h 127.0.0.1, but it didn't work. However, connecting without the -h option worked fine. This suggests there might be an issue with the MariaDB configurati ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

I'm looking to transfer an integer to and from JSON using Java. Can anyone guide me on how to

I have been working on an API that processes HTTP requests and returns JSON reports. To test the functionality, I have experimented with both Java (using HTTPUrlConnection) and Python (using requests). The API itself is developed in Java Spark. I find Pyth ...

Attempting to establish a connection with a RabbitMQ server

I'm diving into the world of message queues and attempting to connect to a RabbitMQ instance that was set up for me using this library. However, I seem to be struggling with it. I followed an example from here and tried to customize it with my own va ...

"Encountering unexpected empty file creation while attempting to utilize Node.js for creating a bucket and pushing an object

As a newcomer to using ExpressJS (built on Node.js) for uploading content to Amazon S3, I followed the provided example from Amazon. However, upon checking the S3 Management Console, I noticed an additional file with the same name as the bucket I just cr ...

What is the best way to extract the value from a JSON object?

My inquiry is about accessing the reverse geocode information Click here for the JSON result Below is the JSON output: { "results":[ { "address_components":[ { "long_name":"Mettupalayam Road", ...

There seems to be an inconvenience with my npm proxy

Encountering issues with proxy services during the installation of packages is frustrating. An error message like this may appear: C:\Users\ihab\Desktop\myApp\myApp>npm install -g npm@latest npm ERR! code ENOTFOUND npm ERR! errno ...

"Error: Attempting to send multiple res.send/json - headers cannot be set after they have already been sent

Is it possible to send multiple res.send/json in the same method? I am facing a challenge as I want to create a function within a Web-Worker to make a put request every minute. However, on the second request, I receive an error message "can't set head ...

In Jenkins on Windows 10, an internal or external command known as Newman is not being acknowledged

I've configured newman in Jenkins to run a Postman collection. For context, I have node js installed at C:\Program Files\nodejs and globally installed newman at C:\Users\waniijag\AppData\Roaming\npm\node_module ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...