12

Here is my code for joining two tables:

DB.from(:sources).join(:payloads, :source_id => :id)

The table names are :sources, :payloads.

The problem is that there is an :id column in payloads which overwrites the :id column in :sources. I need to use an alias so that I just obtain a mega table with all of the column names. However, as currently written and as my tables are currently structured, the :id columns are getting combined and the second table takes precedence. Does this make sense?

How do I make an alias so that the :id column from :sources still shows up?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jwan622
  • 11,015
  • 21
  • 88
  • 181

2 Answers2

7

To alias sources.id to a different name, use the Identifier aliases.

.select_append(:sources__id___source_id).join...
# *, `sources`.`id` AS 'source_id'
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52
  • I prefer using [qualified aliases](https://github.com/jeremyevans/sequel/tree/ca0d2b3d3881bdff612d1349a22aa6c67d0034aa#label-Qualifying+identifiers+-28column-2Ftable+names-29) as `Sequel[:sources][:id].as(:source_id)`. – Daniel Hernández Apr 07 '23 at 16:00
5

I think this is a case where using Sequel's graph will help you.

From the documentation:

Similar to #join_table, but uses unambiguous aliases for selected columns and keeps metadata about the aliases for use in other methods.

The problem you're seeing is an identically named column in one table is colliding with the same column name in another. Sequel's use of graph should make sure that the table name and column are returned as the key, rather than just the column.

The various documentation files have a number of examples, which would make a really long answer, so I recommend going through the docs, searching for uses, and see how they work for you.

Also, the Sequel IRC channel can be a great asset for these sort of questions too.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303