D
D
dfhkjhg2020-11-24 11:57:49
PostgreSQL
dfhkjhg, 2020-11-24 11:57:49

How to add multiple id's to a user from another table?

Suppose there is a user table, the main table where all information about the user is stored

[
name varchar
surname varchar
balance integer
created_at and by the way, which type is better to choose for storing time if the time is stored in the style 1606208106781
books and here there should be a list of user books, their number can be from 0 up to 100
]
and how to make it so that when making a request to get information about the user, I also received information about books (which is stored in another table)
I hope I explained it clearly

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-11-24
@dfhkjhg

created_at and by the way, which type is better to choose for storing time if the time is stored in the style 1606208106781

Why not store time in a specially created timestamp type (even timestamptz)?
If you really want a number, then, apparently, BIGINT.
books and here should be a list of the user's books, their number can be from 0 to 100

This is actually denormalization, which SQL theorists do not like and do not really like ORMs. Think about whether you really need it, because. most solutions will also be poorly portable from one DBMS to another.
And so specifically for postgres, it is best to make the book column of type int [] (int array). It is possible both as a string and to store the id separated by a comma there, but these are already some extra gestures.
how to make it so that when making a request to get information about the user, I also received information about more books

It's easy to do, but there will be duplication of data. For example:
SELECT u.*, b.*
  FROM users u
  LEFT JOIN books b ON (b.id = ANY(u.books))
 WHERE ...

Will output something like:
name    | surname  | balance | created_at       | books     | id    | title             | author
______________________________________________________________________________________________________________
Alex    | Smith    | 22.10   | 1606349583252    | {2,10,88} | 2     | A Game of Thrones | George R. R. Martin
Alex    | Smith    | 22.10   | 1606349583252    | {2,10,88} | 10    | A Clash of Kings  | George R. R. Martin
Alex    | Smith    | 22.10   | 1606349583252    | {2,10,88} | 88    | A Storm of Swords | George R. R. Martin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question