AWS Aurora DB Combine Data from Multiple SQL Statements

Viewed 367

I have three tables with data schema, like:

TABLE user (
    user_id BINARY(16) PRIMARY KEY NOT NULL,
    created DATETIME NOT NULL, 
    last_updated DATETIME,
    coordinator BINARY(16),
    num_updates INT NOT NULL
);


TABLE summary (
    user_id BINARY(16) PRIMARY KEY NOT NULL,
    calculation_time DATETIME NOT NULL,
    calculation_method VARCHAR(25) NOT NULL,
    label VARCHAR(50) NOT NULL,
    critical_count INT NOT NULL,
    median_risk FLOAT(10)
);

TABLE actions(
        user_id BINARY(16) PRIMARY KEY NOT NULL,
        label VARCHAR(50) NOT NULL,
        access_count INT NOT NULL,
        median  FLOAT(10)
    );

The data for all the users (user table) is simply fetched using the lambda handler function in the following manner:

const AWS = require('aws-sdk');
const rdsDataService = new AWS.RDSDataService();

module.exports.hello = async (event, context, callback) => {
  const req_id = "5a9dbfca-74d6-471a-af27-31beb4b53bb2";
  const sql = 'SELECT * FROM user WHERE user_id=:id';

  try {
    const params = {
      resourceArn: 'arn:aws:rds:us-west-********************',
      secretArn: 'arn:aws:secretsmanager:us-west**************',
      sql,
      database: 'dev_db1',
      continueAfterTimeout: true,
      includeResultMetadata: true,
      parameters: [{ 'name': 'id', 'value': { 'stringValue': `${req_id}` } }]
    }

    const db_res = await rdsDataService.executeStatement(params).promise();
    
    const convertToJson = (dbresponse) => {
    const columns = dbresponse.columnMetadata.map(col => col.name);
    const row_data = dbresponse.records.map(row => {
        const json_obj = {};
        row.map((val, i) => {
            json_obj[columns[i]] = Object.values(val)[0];
        });
        return json_obj;
    });
    return row_data;
    };
    
    const modified_data = convertToJson(db_res);

    const response = {
      body: {
        statusCode: 200,
        message: 'Data fetched successfully',
        data: modified_data,
      }
    };

    callback(null, response);

  } catch (error) {
    console.log('Error Received', error);
    const error_res = {
      body: {
        statusCode: error.statusCode,
        message: error.message,
        data: null
      }
    }
    callback(null, error_res);
  }
};

If the same is followed for another table summary or actions, it also works. Now, I need to combine all the columns of these three tables and then return the data (returned rows should match on the basis of req_id). My working snippet: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=016ecc94c792611fbaca810605e81a6a

But the final result obtained contains the column user_id in duplicated form i.e. three times inclusion. I don't need the same column to be repeated thrice.

I am a bit new to handling MySQL queries, so unable to figure out the exact reason for the error even when the table exists. The MYSQL version used in Aurora is 5.7.

Any help to resolve the same is appreciated!

2 Answers

try this

SELECT users.*, summary.* from users, summary WHERE users.user_id = summary.user_id

OR

SELECT * from users, summary WHERE users.user_id = summary.user_id 

Plan A: Explicitly specify the columns you want. Extra benefit: You can get rid of the ids, which tend to be useless to others reading the output.

Plan B: (This option is not always possible.) Instead of JOIN .. ON t1.a = t2.a, say JOIN .. USING(a)

I like to use short aliases. Here's doing all things together:

SELECT  u.last_name,  u.first_name, 
        s.risk_score,
        t.likes
    FROM  user AS u
    JOIN  summary AS s  USING(user_id)
    LEFT JOIN  test AS t  USING(user_id)

In general, it is not wise to have a 1:1 relationship (as you have via user_id); you may as well have all the columns in a single table.

Related