Skip to content

[Question] How to differentiate between fields of the same name coming from different tables in a JOIN ? #2710

@andrei-dascalu

Description

@andrei-dascalu

Consider the schema:

CREATE TABLE `Account` (
  `Id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `Relation` bigint(20) unsigned DEFAULT NULL,
  `Company` varchar(50) DEFAULT NULL,
  `MainAddressId` bigint(20) unsigned not null,
  `AlternateAddressId` bigint(20) default null,
  `CreateDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `ModifyDate` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `Address` (
  `Id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `Address` VARCHAR(200) NOT NULL,
  `City` VARCHAR(80) default null,
  `CreateDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `ModifyDate` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`)
);

and queries

-- name: FindAccountById :one
SELECT * FROM `Account` a
LEFT JOIN `Address` adMain ON a.MainAddressId = adMain.Id
LEFT JOIN `Address` adAlt ON a.AlternateAddressId = adAlt.Id
WHERE a.Id = ?;

when generating the code (mysql driver), the generated method FindAccountById will be returning a custom FindAccountByIdRow where the Id fields coming from different tables are named like Id, Id_2 and Id_3.

I'm not sure if there's something that can be currently done to easily differentiate or have the generated code use table aliases to tell the tables apart (so that the resulting struct elements would be called AdMain_Id and AdAlt_Id respectively . Is there something that can be done to easily manage this situation? Could this be an improvement? Is this something that's more related to the mysql driver than sqlc?

EDIT:

      rename:
        spotify_url: "SpotifyURL"

doesn't seem useful in this case. The name of the resulting struct field depends on context (eg: every table may have an ID, but whether it ends up being Id_2 or Id_3 depends on the exact query and what joins happen).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions