Break up the combined result set into individual rows

In my stored procedure, I am processing records from specific tables. As part of this process, I am using a temporary table to store results generated by join operations.

Let's take a look at the structure of Table A:

+----+------+--------+
| id | name | number |
+----+------+--------+
|  1 | John |    123 |
|  2 | Tim  |    567 |
|  3 | Bill |    789 |
|  4 | Jim  |    345 |
+----+------+--------+

Now, let's explore Table B:

+----+------+--------+
| id | code | number |
+----+------+--------+
|  1 | LK   |    123 |
|  2 | CN   |    123 |
|  3 | BN   |    789 |
|  4 | IN   |    345 |
+----+------+--------+

Lastly, here is Table Temp which contains the combined result set:

+----+------+-----+------+--------+
| id | name | age | code | number |
+----+------+-----+------+--------+
|  1 | John |  54 | LK   |    123 |
|  1 | John |  54 | CK   |    123 |
|  3 | Bill |  26 | BN   |    789 |
|  4 | Jim  |  78 | IN   |    345 |
+----+------+-----+------+--------+

The next step is to convert the result set in Table Temp to JSON format:

[{"id":1,"name":"John","code":"LK","number":123}, {"id":2,"name":"John","code":"CK","number":123}, {"id":3,"name":"Bill","code":"BN","number":789}, {"id":4,"name":"Jim","code":"IN","number":345}]

I now aim to display these records in a particular layout. Here's how I want it to appear:

+------------+-----+------+--------+
|    name    | age | code | number |
+------------+-----+------+--------+
| John       |  54 |      |        |
|            |     | LK   |    123 |
|            |     | CK   |    123 |
| Bill       |  26 |      |        |
|            |     | BN   |    789 |
| Jim        |  78 |      |        |
|            |     | IN   |    345 |
+------------+-----+------+--------+

[{"name":"John","age":54}, {"code":"LK","number":123}, {"code":"CK","number":123}, {"name":"Bill","age":26}, {"code":"BN","number":789}, {"name":"Jim","age":78}, {"code":"IN","number":345}]

My question arises on how best to split and organize this JSON data for viewing purposes, or if there is a way to directly query and generate this structured result set from Table Temp in MySQL?

Answer №1

-- Here is the requested query:
select 
    if(name = @last_name, '', @last_name := name) as name,
    if(age = @last_age, '', @last_age := age) as age,
    code,
    number
from
(   
    (select name, age, code, number from t)
    union 
    (select distinct name, age, '', '' from t)
    order by 1,2,3,4
) as t2 cross join (select @last_name := null, @last_age := null ) param; 

Demonstration of the Query:

SQL Examples:

-- Creating table and inserting data
create table t(id int, name char(20), age int, code char(20), number int);
insert into t values
(  1 , 'John' ,  54 , 'LK'   ,    123 ),
(  1 , 'John' ,  54 , 'CK'   ,    123 ),
(  3 , 'Bill' ,  26 , 'BN'   ,    789 ),
(  4 , 'Jim'  ,  78 , 'IN'   ,    345 );
select * from t;

-- The desired query
select 
    if(name = @last_name, '', @last_name := name) as name,
    if(age = @last_age, '', @last_age := age) as age,
    code,
    number
from
(   
    (select name, age, code, number from t)
    union 
    (select distinct name, age, '', '' from t)
    order by 1,2,3,4
) as t2 cross join (select @last_name := null, @last_age := null ) param
; 

Result Output:

mysql> select * from t;
+------+------+------+------+--------+
| id   | name | age  | code | number |
+------+------+------+------+--------+
|    1 | John |   54 | LK   |    123 |
|    1 | John |   54 | CK   |    123 |
|    3 | Bill |   26 | BN   |    789 |
|    4 | Jim  |   78 | IN   |    345 |
+------+------+------+------+--------+
4 rows in set (0.00 sec)

mysql> -- The desired query
mysql> select
    -> if(name = @last_name, '', @last_name := name) as name,
    -> if(age = @last_age, '', @last_age := age) as age,
    -> code,
    -> number
    -> from
    -> (
    -> (select name, age, code, number from t)
    -> union
    -> (select distinct name, age, '', '' from t)
    -> order by 1,2,3,4
    -> ) as t2 cross join (select @last_name := null, @last_age := null ) param
    -> ;
+------+------+------+--------+
| name | age  | code | number |
+------+------+------+--------+
| Bill | 26   |      |        |
|      |      | BN   | 789    |
| Jim  | 78   |      |        |
|      |      | IN   | 345    |
| John | 54   |      |        |
|      |      | CK   | 123    |
|      |      | LK   | 123    |
+------+------+------+--------+
7 rows in set (0.00 sec)

Answer №2

In my opinion, this question appears to be more about formatting the output rather than querying the database. Personally, I would opt for using JavaScript on the client side to achieve the desired output format.

If SQL is preferred, I would choose to avoid utilizing a temporary table. Instead, I would combine information from the two original tables through a union operation and arrange the final result set accordingly. On the client side, only the id column would need to be concealed:

(SELECT id, name, age, null as code, null as number
 FROM table1)
UNION
(SELECT id, null, null, code, number
 FROM table2)
ORDER BY id ASC, name DESC

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

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

Attach an event to a dynamically created form

I am experiencing an issue with binding the submit event to a newly created form in my functions. The first function calls a form, and the second submits that form via ajax. However, I can't seem to successfully bind the submit event to the new form. ...

Looking to add a close button to the iFrame, but having trouble getting it to function when clicked

In my project built with Meteor, I have integrated an iframe to display specific content to the user. The iframe is functioning as expected, but I am looking to add a close button that will effectively unload the iframe when clicked. I attempted to imple ...

"Customize your search experience with a bootstrap search bar featuring multiple input fields

Currently working on a website using Bootstrap and trying to create a filter bar for the items displayed on the page. I am looking to include one or more input fields (highlighted in red) and one or more dropdowns (highlighted in blue). The width of the ba ...

What is causing the recursion function to return "NaN" in this scenario?

I'm trying to calculate the total sum of absolute differences between consecutive elements in an array using a function called sumAbsArr, but it seems to be returning NaN. var arr = [1, 5, 2]; var n = 3; var cur = 0; console.log(sumAbsArr(arr, n, ...

Implementing an automatic table data update with Ajax, Json, and Node.js

I am currently utilizing Node.js on the server-side with Express and Twitter Bootstrap on the front-end. The webpage features a dialog box with a form and a submit button; the form is submitted using a jQuery Ajax call to prevent page reload after receivin ...

Determine the total cost of a shopping cart with just a single query in SQL

Usually, I just have a basic shopping cart containing various items with quantities listed. However, I am interested in implementing the following query: SELECT SUM(price * quantity) as total FROM products WHERE product_id IN (1,2,3,4); My concern is how ...

Using PHP's $_GET with an Ajax/Jquery Request

I've been struggling to set a variable $id=$_GET["categoryID"] and can't seem to make it work. I suspect it's related to the Ajax request, but I'm unsure how to format it correctly to work with the request for my mysql query. Any assist ...

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

Issues encountered during the installation of Electron JS

Having trouble installing electronjs in Node.js 18 LTS and NPM 10? Getting an error message like this? PS C:\Users\Administrator.GWNR71517\Desktop\electron> npm install electron --save-dev npm ERR! code 1 npm ERR! path C:\Users& ...

Stay put, conceal, and revert selected option according to the button

Apologies for the confusion with the title of this section. I want to hide certain select options until a user selects a specific button. Once a button is selected, I want the corresponding select field to remain visible. However, if the user chooses a di ...

Quickest method for importing a CSV document into MYSQL

Uploading a CSV file to MySQL can be time-consuming, especially with large amounts of data. This process involves truncating the table, reading the file, and importing each row one by one. $deleterecords = "TRUNCATE TABLE discount"; mysql_query($deletere ...

Is it possible to automatically identify json-schema.org for a json/yaml file?

Reviewing this document: --- # CI E2E test configuration for locally built images and manifests including: # - cluster-api # - bootstrap kubeadm # - control-plane kubeadm # - hetzner # To generate local development images, use make e2e-image from the main ...

"Combining two strings to display in a single TextView: A step-by-step

Looking to populate a TextView with 2 Strings of JSON data. example.json { "volumeInfo": { "title": "Computer Architecture", "subTitle": "A Quantitative Approach" } From the JSON provided, I would like my TextView to display: Computer Architectur ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...

The imported MySQL ENUM column does not seem to align with the quoted values on a different machine

After importing a new database to work on my local machine, I encountered an issue: the ENUM column only functions when the variable is sent without quotation marks. See the example below: mysql.local>select count(*) from psh_products where active = 1; ...

Unraveling JSON through DOJO AJAX and REST techniques

I have been attempting to send a request to a REST server using DOJO AJAX, but unfortunately I am receiving a null object as the result in the console: When CLICKED = click clientX=34, clientY=13 JSON loaded from server: null Below is the code snippet I ...

Utilizing code sharing by embedding a query within a stored procedure

What follows is abstraction. Queries are more intricate but the principle remains the same. I currently have a Stored Procedure that executes the following query: SELECT * FROM T1 WHERE T1.fk IN (SELECT id FROM T2); The inline query mentioned is quite c ...

Massive Data Processing in Java Leading to Memory Leakage

I am in the process of developing a software application that deals with processing multiple files, each containing approximately 75,000 records in binary format. Whenever I run this application manually, which is usually done once a month, it processes ar ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...