What is the most effective way to combine data entries with identical IDs into a unified entry?

My MySQL and Typeorm skills are at a beginner level. When I run my query, it returns data with duplicate IDs like:

[
  {
    id: "1",
    name: "john",
    place: "San Francisco"
  },
  {
    id: "1",
    name: "john",
    place: "Mumbai"
  }
]

What I'm looking for is to retrieve unique entries based on ID, such as:

[
 {
  id: "1",
  name: "john",
  place: ["San Francisco", "Mumbai"]
  }
]

I need help understanding how to use groupBy to achieve this desired result. Can anyone assist me?

Answer №1

While obtaining an array directly may not be possible, an alternative approach could involve utilizing group_concat. One potential query structure is as follows:

SELECT `id`, group_concat(`name`), group_concat(`place`) FROM <table_name> GROUP BY `id`

If individual names are not required to be concatenated

SELECT `id`, `name`, group_concat(`place`) FROM <table_name> GROUP BY `id`

In your code implementation, you can then split the resulting string into an array. The separator used can either be the default ',' or a custom one like '!#$!'

Answer №2

To achieve the desired output in MySQL, you can utilize the GROUP_CONCAT function:

SELECT 
  id, name, GROUP_CONCAT(place) 
FROM 
  <table_name> 
GROUP BY 
  id

If you are working with TypeScript, you can make use of Array.prototype.reduce():

const data = [{id: "1",name: "john",place: "San Francisco"},{id: "1",name: "john",place: "Mumbai"}]

const dataHash = data.reduce((a, { id, name, place }) => {
  a[id] = a[id] || { id, name, place: [] } 
  a[id].place.push(place)
  return a
}, {})
const result = Object.values(dataHash)

console.log(result)

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

Exploring various tables in Mysql for search purposes

I am currently in the process of developing a search functionality that allows users to explore studies based on specific elements. In my database, I have two tables: elements and studies. The elements table contains key elements related to the study, su ...

Recursion in Angular2 components causes emit to malfunction in child components

In my Angular2 (Typescript) app, I have integrated a 'tree' list of categories. This feature allows users to click on a category name, whether it's a main category or sub-category, and view the related products. The 'category-tree&apos ...

PHP Prepared Statement Failing While Executing MySQL Function

For some time now, I have been using prepared statements without any issues. However, today when I attempted to call a MySQL function from a prepared statement, I encountered the following error: Fatal error: Call to a member function fetch_array() on boo ...

What is preventing me from modifying database information by deselecting checkboxes in CodeIgniter?

Recently, I came across a simple forum project on a website: CIBB Basic Forum with Codeigniter However, I encountered an issue while working on this project involving checkboxes. The problem seems to stem from the original code provided on the website, a ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

Error: Unable to find provider for Store in Angular 9 AuthService Guard

I have been working on implementing an Auth guard with Angular 9, but I encountered an ERROR in the browser console: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(SampleModule)[AuthGuard -> Store -> Store -> Store -& ...

Searching for comma-separated values in CakePHP can be accomplished by using the `FIND

Seeking assistance with CakePHP In a table, I have a field called furnished_details with the following content (separated by commas): Double Bed,Flat TV : small (19"),Mirror,Extra storage,Window AC,Ceiling Fan,Lamp,Chair,Armoire,Mini-Fridge When an ad ...

If the value is not empty, then utilize the keyword "where"

The objective Utilize the "where" clause only when the parameter is not null. The issue I am unsure of the correct syntax to use. What I currently have Below is the syntax that is not functioning correctly. CREATE DEFINER=`root`@`localhost` PROCEDURE ...

Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript: $('.switch').click(()=>{ $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=& ...

Show data rows on a website by utilizing a custom function that utilizes mysqli for fetching data

Within my PHP code, I have a function that utilizes mysqli to fetch data from a database. This is what the function looks like: function displayUserInfo(){ $db = mysqli_connect("localhost", "root", "", "shop") or die("Error"); $query = "SELECT ...

Enhancing systemjs-builder with DefinitelyTyped

Is there a dedicated TypeScript definition file for systemjs-builder available? https://github.com/systemjs/builder I encountered an issue where the systemjs.d.ts file does not seem to cover it, leading to a "cannot find module" error when trying to impor ...

Error: The function mysql_num_rows() is causing a Segmentation fault

While attempting to run a MySQL query in C, I encounter a Segmentation fault when calling mysql_num_rows() function. Below is the code snippet being used: char *username = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30445 ...

SQL Select records between AAA and ZZZ

I am having trouble retrieving codes that fall between AAA and ZZZ. Here is the code I attempted to use: ALTER TABLE AIRPORT ADD CONSTRAINT CORRECTCODE CHECK (Code BETWEEN 'AAA' AND 'ZZZ' AND LENGTH(Code) = 3) ENABLE VALIDATE; While i ...

Retrieve information from two text input fields

My SQL query looks like this: $select = "SELECT * FROM products WHERE name LIKE '$search%' AND price > '$price'"; Unfortunately, the results are not what I expected. If you need more information about the database structure, check ...

Querying MySQL to locate unread messages for email users

I have a basic email database comprising of two tables: EMAIL and EMAIL_MESSAGES. EMAIL & EMAIL_MESSAGES CREATE TABLE IF NOT EXISTS EMAIL ( MAIL_NO TINYINT UNSIGNED NOT NULL, BIZ_ID VARCHAR(35) CHARACTER SET 'latin1' COLLATE &apos ...

How can I correctly annotate property 'firebase' on type '{ children?: ReactNode; }' in order to resolve the error?

My firebase object is provided through a higher order component as shown below: const FirebaseContextInterfaceLocal: FirebaseContextInterface = { value: new Firebase() } ReactDOM.render( <Router history={history}> <FirebaseContext.Provi ...

Is there a way in TypeScript to prevent the modification of a class property and still trigger a runtime error if attempted?

I currently have the following code snippet: class Computed<Value> { _value: Value; get value(){ return this._value; } } When attempting to set the value property, TypeScript returns an error message: Cannot assign to value because it is ...

I need to eliminate excess trim from the query in order to optimize the efficiency of fetching data

My question is: select * from PERSON where trim(person_name) = trim(Filter(name)) and trim(person_id) = trim(filter(ID)) . I am looking to enhance performance by removing the use of trim function. Are there any alternative solutions? ...

Setting up "connect-redis" in a TypeScript environment is a straightforward process

Currently, I am diving into the Fullstack React GraphQL TypeScript Tutorial I encountered an issue while trying to connect Redis with express-session... import connectRedis from "connect-redis"; import session from "express-session"; ...

"Enhance Your Data with ADO.NET's SqlDataAdapter to Update One Record

Currently, I am utilizing a SqlDataAdapter on a Windows Form using C#. Through a BindingSource, I have successfully connected it to my fields with the ability for functional record navigation and saving modifications back to the database. I am interested ...