Sample Header Ad - 728x90

Database Administrators

Q&A for database professionals who wish to improve their database skills

Latest Questions

3 votes
1 answers
276 views
How to "merge" rows along with their foreign many-to-many relations without violating unique constraints?
Fiddle: https://dbfiddle.uk/-JLFuIrN ## Table ```postgresql CREATE TABLE files ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text ); CREATE TABLE folders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text ); CREATE TABLE file_folders ( id bigint GENERATED ALWAYS AS IDENTITY...
Fiddle: https://dbfiddle.uk/-JLFuIrN ## Table
CREATE TABLE files (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text
);

CREATE TABLE folders (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text
);

CREATE TABLE file_folders (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  file_id bigint NOT NULL REFERENCES files,
  folder_id bigint NOT NULL REFERENCES folders,
  UNIQUE (file_id, folder_id)
);
## Query
/*
  Merges
*/

WITH targets AS (
  SELECT 
    ARRAY (
      SELECT
        id
      FROM
        folders TABLESAMPLE BERNOULLI (50)
      LIMIT 3
    ) AS folders
),
-- basically a setup to ensure unique target/folder pairs
-- and no targets in the merges
input_folders AS (
  SELECT
    folders.id AS folder_id,
    random_array_element(targets.folders) AS target_id
  FROM
    folders
    CROSS JOIN
    targets
  WHERE
    NOT ( 
      folders.id = ANY (targets.folders)
    ) 
),
input_files AS (
  SELECT
    file_folders.id,
    file_folders.folder_id,
    file_folders.file_id,
    input_folders.target_id
  FROM
    input_folders
    INNER JOIN
    file_folders
    ON
      input_folders.folder_id = file_folders.folder_id
      OR
      input_folders.target_id = file_folders.folder_id
),
deleted_files AS (
    WITH deletions AS (
    SELECT
      inputs.id
    FROM
      input_files AS inputs
      INNER JOIN
      input_files AS targets
      ON
        NOT (inputs.folder_id = targets.target_id)
        AND
        inputs.file_id = targets.file_id
  )
  DELETE
  FROM
    file_folders
  WHERE
    id IN (
      SELECT
        id
      FROM
        deletions
    )
),
merged_files AS (
  WITH merges AS (
    SELECT
      inputs.id,
      inputs.folder_id,
      inputs.target_id
    FROM
      input_files AS inputs
      INNER JOIN
      input_files AS targets
      ON
        NOT (inputs.folder_id = targets.target_id)
        AND
        NOT (inputs.file_id = targets.file_id)
  )
  UPDATE file_folders
  SET
    folder_id = merges.target_id
  FROM
    merges
  WHERE
    merges.id = file_folders.id
),
deleted_folders AS (
  DELETE
  FROM
    folders
  WHERE
    id IN (
      SELECT DISTINCT
        folder_id
      FROM
        input_folders
    )
)
SELECT
  folders AS targets
FROM
  targets
;
## Inputs The array-transforming setup is me trying to replicate the JSON input of the application in pure SQL. The input looks like this:
interface IQueryInput extends Array {};

interface IMergeInput {
  target: IEntityID;
  inputs: IEntityID[];
};

// postgresql bigints are treated as strings in the application
type IEntityID = string;
So the prepping query from above can be replaced with:
WITH inputs AS (
  SELECT
    input.*
  FROM
    -- the application interpolates JSON there
    json_to_recordset($inputs$$inputs$) AS input(
      target bigint,
      inputs bigint[]
    )
),
input_folders AS (
  SELECT
    inputs.target AS target_id,
    merge.folder_id
  FROM
    inputs
    CROSS JOIN
    UNNEST(inputs.inputs) AS merge(
      folder_id
    )
)
It must run as a batch operation, so the application provides these guaranties for the query input: - all target values are unique. - all inputs concatenated result in unique values. - target values do not intersect with concatenated inputs. Therefore input_folders always ends up as unique target_id-folder_id pairs. The query is ran as a background task, so the speed and memory are of secondary importance. The main requirement is of a typical transaction: either it should go through completely on success or reject completely on any error. ## The problem I want to "merge" several folders into a single folder. So given a target_id and an array of folder_ids, replace all foreign references to folder_ids with target_id and remove non-target folder afterwards.
This however becomes an issue in relations table with unique constraints, since after updating the references there are duplicates.
So I went this path: 1. Select all relation rows related to the query, so all file_folders with target_ids and folder_ids in them. 2. Separate them into two categories: - Deletes - the rows which will result in dupes when updated. - Merges - the rows which will not result in. 3. Delete the delete candidates. 4. Update the merge candidates. 5. Repeat previous 4 steps for all relations. 6. Delete rows in folders with folder_ids. However I still stumble upon unique key violation error.
"Merge" is in quotes because it doesn't look like what I am trying to do can be accomplished by [merge in docs](https://www.postgresql.org/docs/15/sql-merge.html) and it requires a newer version of postgresql anyway.
Biller Builder (288 rep)
Jan 13, 2023, 02:47 PM • Last activity: May 17, 2025, 05:08 PM
1 votes
3 answers
340 views
Putting foreign keys of several tables into the same column
I've never come across this situation, not sure how to go about it. Let's say I have a table `Portfolio`. I also have two tables: `Asset 1`, and `Asset 2`. I need to create a bridge between `Portfolio` and the `Asset` tables. A portfolio can have either `Asset 1`, or `Asset 2`, or both, or none. [![...
I've never come across this situation, not sure how to go about it. Let's say I have a table Portfolio. I also have two tables: Asset 1, and Asset 2. I need to create a bridge between Portfolio and the Asset tables. A portfolio can have either Asset 1, or Asset 2, or both, or none. enter image description here Can I do something like the bridge table in the image above, i.e. where the bridge table (example below) would contain in the same column, the foreign keys to two different tables enter image description here
George Well (31 rep)
May 19, 2020, 02:55 PM • Last activity: Apr 30, 2025, 01:10 AM
0 votes
1 answers
705 views
Table Relationships for Property Bags Configuration
I am creating a database table setup for user preferences in my application based partially on this [design][1] and while I created the tables and foreign keys, I can't seem to figure out the relationships of these tables. The attached screenshot is the DB design and below is what I currently believ...
I am creating a database table setup for user preferences in my application based partially on this design and while I created the tables and foreign keys, I can't seem to figure out the relationships of these tables. The attached screenshot is the DB design and below is what I currently believe are the correct relationships user preferences user to user_preference = one-to-many user to preference = many-to-many user_preference to user = many-to-one user_preference to preference = many-to-one user_preference to allowed_preference_value = many-to-one preference to allowed_preference_value = one-to-many
cphill (115 rep)
Dec 28, 2018, 06:46 PM • Last activity: Apr 24, 2025, 09:00 AM
1 votes
1 answers
1057 views
ER Diagram | Group, Post, User relationship
I need to design an ER diagram, but I am confused in a section, more specifically how to relate the post with the groups, because I need that post contains the information of in which group I publish and that user I publish it, I have two diagrams one where the relation of post, group and user are d...
I need to design an ER diagram, but I am confused in a section, more specifically how to relate the post with the groups, because I need that post contains the information of in which group I publish and that user I publish it, I have two diagrams one where the relation of post, group and user are direct, and other where the post is related by means of the table generated of the relation many to many between group and user. My question is which of these two is more recommended. Diagram A Diagram A Diagram B enter image description here
ontimond (111 rep)
Sep 4, 2020, 04:29 PM • Last activity: Apr 12, 2025, 08:05 PM
2 votes
2 answers
573 views
Modeling an either/or relationship
I've seen this post ([How should I model an “either/or” relationship?][1]) but it's not exactly what I'm looking for. both answers are suggesting creating a subtype instead of a relationship. Say I have an entity `MACHINE`, and I want to creat a relationship to connect it with another entity `OS`, c...
I've seen this post (How should I model an “either/or” relationship? ) but it's not exactly what I'm looking for. both answers are suggesting creating a subtype instead of a relationship. Say I have an entity MACHINE, and I want to creat a relationship to connect it with another entity OS, call it "installs" or whatsoever. And this OS has 2 subtypes: WINDOWS and MAC *(Linux and Unix also work but just for demo purpose they are not included)*. Not considering virtual machine or double OS, I can only choose one of these 2 subtypes of OS, how should I model this in the entity-relationship model? demo img Should I - Create 1 relationship between MACHINE and OS. Or - Create 2 relationship between MACHINE and WINDOWS, MACHINE and MAC. Or - Create 1 ternary relationship between MACHINE, WINDOWS and MAC. And should I add additional attributes to the entities or the relationship? Thanks:D
Amarth Gûl (121 rep)
Sep 10, 2020, 02:52 AM • Last activity: Apr 8, 2025, 07:08 PM
1 votes
1 answers
49 views
(How) Can MySQL (MariaDB) update relations when moving entry between tables?
I am facing an issue while creating a DB (in MariaDB) for a university research group. I am currently designing which tables I need for this. The goal is to be able to put a web interface on top of this DB in the future where the leader (professor) of the group can log in and see all his staff, stud...
I am facing an issue while creating a DB (in MariaDB) for a university research group. I am currently designing which tables I need for this. The goal is to be able to put a web interface on top of this DB in the future where the leader (professor) of the group can log in and see all his staff, students, publications, etc. and change stuff (kick out a student, for example) while the other scientists in the group can do different things there. For example: A student should only be able to edit his stuff (email, name, etc) or a senior scientist should be able to assign students to projects, etc. My question now come from the way I handle the "people" table(s). My first idea was to make a table for "staff" (people that get paid and have a contract with the university) and one for "students" (people that do not have a contract, maybe are just guests or just there for a few months for a thesis, etc). Now the problem is: It happens quite often that former students later get hired by the professor and therefore (in this DB design) should move from the "students" table to the "staff" table. However, this would destroy (unlink?) all their relations that they had in the "students" table to other tables (like for example "publications" table for the publications they published while they were still a student). Is there any way in MySQL to move an entry from one table to another and automatically (or reasonable easily by hand) update all their relations to any other tables in the database? Concrete example: Student Benjamin with "student_id" 75 moves from "students" table to "staff" table and gets "staff_id" 188 there. Is there a way to automatically replace "students.student_id 75" with "staff.staff_id 188" throughout the entire database to keep his old relations alive? Should he even be MOVED from "students" to "staff" table or rather be kept in the "students" table (with an "inactive" flag or something) and just get copied to the "staff" table with a new ID? That would make him redundant in the DB, right? Or would it make more sense to create just one "persons" table and manage their status via a "role" column or "persons_to_roles" link table? Ideally, I wanted to have separate tables for "students" and "staff", so I can give the web apps that the students use only write access to the "students" table and not the "staff" one. Thanks for any help!
rokyo (11 rep)
Mar 18, 2025, 12:14 PM • Last activity: Mar 19, 2025, 03:09 PM
0 votes
0 answers
64 views
PostgreSQL insert to multiple tables while keeping relation between their rows
I'm trying to insert a dataset to two tables (a and b) while trying to keep correlation between the rows (b.id_a). Does anybody have any idea how to set foreign key (id_a) in "inserted_b"? ```sql BEGIN; CREATE TABLE a( id SERIAL PRIMARY KEY, col_a INT ); CREATE TABLE b( id SERIAL PRIMARY KEY, id_a I...
I'm trying to insert a dataset to two tables (a and b) while trying to keep correlation between the rows (b.id_a). Does anybody have any idea how to set foreign key (id_a) in "inserted_b"?
BEGIN;
CREATE TABLE a(
	id SERIAL PRIMARY KEY,
	col_a INT
);
CREATE TABLE b(
	id SERIAL PRIMARY KEY,
	id_a INTEGER REFERENCES a(id),
	col_b INT
);
WITH
input(idx,col_a,col_b) AS (
	VALUES (0, 0, NULL), (1, 1, 0)
),
inserted_a AS (
	INSERT INTO a(col_a)
	SELECT col_a FROM input
	RETURNING *
),
inserted_b AS (
	INSERT INTO b(col_b)
	SELECT col_b FROM input
	WHERE input.col_b IS NOT NULL
	RETURNING *
)
SELECT *
FROM a
LEFT JOIN b ON b.id_a = a.id;
ROLLBACK;
I was thinking about returning that extra generated "idx" column within _inserted_a_, but i can't use RETURNING for anything that had not been inserted.
shd (1 rep)
Mar 12, 2025, 07:58 AM
2 votes
1 answers
205 views
Please help me understand this problem about cardinality
Me and my friend are in the process of creating an ER diagram for a professional soccer league, we are both very new to Database so we aren't sure if everything we do is correct. When creating a relationship between a manager and a club, he made this: [![diagram][1]][1] I'm quite confused about why...
Me and my friend are in the process of creating an ER diagram for a professional soccer league, we are both very new to Database so we aren't sure if everything we do is correct. When creating a relationship between a manager and a club, he made this: diagram I'm quite confused about why the 2 relationships managedBy and signsWith are Many to Many. My friend said that multiple managers can manage multiple clubs, one-on-one at a time. But shouldn't that be One to One instead? Since at any moment in time, a club can only have a single manager managing it and a manager can only have a single club to manage (we do not care about assistant manager in this instance); same thing about the signsWith relationship. So which one of us is right?
it's not me (23 rep)
Sep 27, 2024, 11:38 AM • Last activity: Sep 27, 2024, 12:31 PM
-2 votes
1 answers
20 views
An establishment schema, with a single user owner and many user employees
I have an unchangable user table which stores user data, depending on the role(A 1-M connection with the roles table) the user could be either an establishment worker or an establisment owner. I need to add the establishment, where the establishment could have a single owner but many workers. What's...
I have an unchangable user table which stores user data, depending on the role(A 1-M connection with the roles table) the user could be either an establishment worker or an establisment owner. I need to add the establishment, where the establishment could have a single owner but many workers. What's the Ideal solution for this issue?
koogel (1 rep)
Sep 6, 2024, 08:40 AM • Last activity: Sep 6, 2024, 10:47 AM
0 votes
1 answers
52 views
primary key referened by only single foreign key of another table among multiple tables that can reference it
Let's say I have table Account that contains username and password of users to login:- ```sql account ( account_id BIGINT PRIMARY KEY, username VARCHAR(30), password VARCHAR(30) ) -- I have two more tables that stores their credentials in the above table:- customer ( delivery_address VARCHAR(100), a...
Let's say I have table Account that contains username and password of users to login:-
account (
    account_id BIGINT PRIMARY KEY,
    username VARCHAR(30),
    password VARCHAR(30)
)

-- I have two more tables that stores their credentials in the above table:-

customer (
    delivery_address VARCHAR(100),
    account_id FOREIGN KEY,
    ..30 more customer columns
)

admin (
    sp_admin_code INT,
    account_id FOREIGN KEY,
    ..30 more admin columns
)
An admin cannot be a customer and use same username and password to login as a customer. My Questions:- 1. Is this the proper way to implement this kind of relationship? If not, what is? 2. Do I need to add some constraint in the primary key of the account table to denote that it's single entry can either be referenced by customer table or by admin table at once? 3. Now we also know that, an entry on account can only exist if there is an entry for it on either customer table or admin table and vice versa. So do we need to or if we want do add some cascade/constraint, how do we do it or how should we do it or if we should do it at all? sorry im confused.. thank you!
Sidharth Bajpai (103 rep)
Jun 15, 2024, 08:53 AM • Last activity: Jun 15, 2024, 12:56 PM
0 votes
2 answers
7154 views
System/database design for comments/replies and upvotes at scale
Recently I started discovering a topic around "How to design db schema for storing structures similar to Instagram/Facebook/Reddit comments?". After extensive research, I was able to find a bunch of different answers on SO, SE, medium articles and etc. Meanwhile, all of these articles were pretty ba...
Recently I started discovering a topic around "How to design db schema for storing structures similar to Instagram/Facebook/Reddit comments?". After extensive research, I was able to find a bunch of different answers on SO, SE, medium articles and etc. Meanwhile, all of these articles were pretty basic and always point out a Closure table pattern , which I used once back in the day. I did implement a comments/replies system only once a few years ago using PostgreSQL and since then the product is already not in production, so I don't know how my solution would scale in a data-intensive environment. Therefore, I decided to ask a specific question with specific requirements and constraints, so I could probably get a hint from someone who had this experience in production! Here we go with two different tasks: **Task 1** *Requirements:* - When I open a post I see only the first level of comments. In particular, 50 most liked comments are ordered ascending by the number of likes. - For every top-level comment: if a comment has only one reply - display this reply too. - For every top-level comment: if a comment has multiple replies, display only the one which is the most liked. - When the user clicks on "more replies": Display replies in descending order by their created_datetime. - The max depth is 2: Only the top-level comment and replies to it can exist. Replies to lower-level comments(depth == 0) should always be displayed near their parents. The only thing that distinguishes them is just a mention of a user you reply to, like @ on instagram. *Questions(only related to the design of relational database with Closure table):* - What are the problems you faced in **production** with it and how you had to fix them? What would you recommend to people who just start with this, what should they spend their time on at the beginning to prevent a cascade of mess in the future? - Is there a better pattern with RDBS nowadays for this purpose? Let's imagine the system grows. We don't talk about thousands of requests, but we talk about hundreds of thousands of comments and replies to them. E.g. some celebrity posted a message and then all the fans started replying, having conversations and etc. It results in a lot of rows in our records in both the comment and closure tables. Our queries to group by amount of likes start getting much slower on some posts, causing long-running transactions which cause a ton of mess and even probably downtimes. Again, that's what it looks to me that could happen if we just use a closure table. But what really happens? Curious to hear stories of people who had problems with it in really data-intensive applications. E.g. We can shard the table somehow, right? Or for really big posts we could cache a lot of stuff, right? **Task 2** - The main difference to the first one: When I open a post I see 50 most liked comments but with all their children. Meaning I fetch the whole tree for these 50 first comments. Depth is not limited. *Questions(only related to the design of relational database with Closure table):* - Should we simplify the logic and become less ambitious, so we would go with business requirements similar to the ones in task 1? (when we don't have infinite depth and comments trees can grow only in width) I assume otherwise this is almost impossible to scale such a business logic when there are millions or billions of comments. - If the answer to the first question is no, how the magic happens then? ( I don't believe that such product requirements could be scalable while infrastructure would still stay profitable; costs would grow exponentially imo) **General questions to be answered first:** - Is a relational database still a case for such a problem nowadays? I don't know much about graph databases, but wouldn't it be optimal to store such hierarchical data there? Probably I just need to discover graph databases deeper, so please feel free to link the related articles. Doesn't seem I found them in a week, so I would definitely need help with finding the right materials :) **To sum up:** I understand that my questions may seem pretty vague, but they are also quite complex and require the knowledge of someone who had this experience. Meanwhile, I am also quite opinionated on some topics (like growth of costs/sharding/caching) and that's why it is even more difficult for me to compile the opinion - I wanna have more thoughts gathered, not only mine. In case you think an extensive answer would take too much of your time - please give me just short answers like yes or no and just link all the resources you think could really help me to build my opinion on this topic. Sharing your real production experience of working with such systems would be really helpful and appreciated! Thanks!
IDobrodushniy (1 rep)
Sep 10, 2022, 05:06 PM • Last activity: Mar 28, 2024, 08:24 AM
2 votes
0 answers
25 views
Is there an algorithmic way to identify potential primary key foreign key relationships in postgres
I have a lots of tables in postgres with a lots of columns per each table. I need to write a program in such a way that it can identify the columns that can be a potential primary and foreign key pair. The way I'm achieving this right now is by iterating through every combination and comparing colum...
I have a lots of tables in postgres with a lots of columns per each table. I need to write a program in such a way that it can identify the columns that can be a potential primary and foreign key pair. The way I'm achieving this right now is by iterating through every combination and comparing columns based on their distinct data. the pseudocode is something like this: for(int i=0;i
Ashwin Prasad (21 rep)
Dec 20, 2023, 06:00 AM
0 votes
1 answers
52 views
Possible options for SQL and NoSQL combination for social media data
I have searched this forum for an answer but could not find anything relevant. We are designing database schemas for a social media app with posts, groups, users and chats etc and it looks like we have a mix of structured and unstructured data so initially decided to go with PostgreSQL and Mongo. We...
I have searched this forum for an answer but could not find anything relevant. We are designing database schemas for a social media app with posts, groups, users and chats etc and it looks like we have a mix of structured and unstructured data so initially decided to go with PostgreSQL and Mongo. We also have to restrict some data to some regions because of compliance and regulations but allow the rest of the data globally because of users moving around globally. Since we don't have anything critical like a bank, we are wondering if we just have to go with Mongo all the way as it makes our business logic, deployment and maintenance simple and fast. One issue is the many-many relations like user belongs to many groups and a group has many users. In relational, I could have a table with rows (group_id and user_id) and I can easily get all users in a group or all groups a user is in. In unstructured, I can store groups list in user's document and users list in group's document but now if a user joins a group, it becomes two updates (user's document and group's document). Same logic for user liking a post. Here we want all users who liked a post and all posts that the user liked. Even if one does not need one piece of information in real-time such as the app never shows the groups a user is in to the user, we might need it for data analysis which means we have to extract this from reading all groups' documents. We also feel PostgreSQL is cheaper when looking at AWS RDS vs MongoDB Atlas, so tempted to at least use it partially. Could anyone please let us know if there is an elegant solution for this or any blogs, posts that gives a solution? Regards, KSRD
dksr (101 rep)
Nov 30, 2023, 11:03 AM • Last activity: Nov 30, 2023, 01:44 PM
1 votes
1 answers
89 views
How can I SELECT columns from one table that corresponds with a column of another table on JOIN without creating a relation between the tables?
I have 3 tables: ```postgresql CREATE TABLE catalog.shoes ( shoe_id SERIAL PRIMARY KEY, brand VARCHAR(255) NOT NULL, model VARCHAR(255) NOT NULL, price INT NOT NULL, CONSTRAINT shoe_name UNIQUE (brand, model) ); CREATE TABLE catalog.stock ( item_id SERIAL PRIMARY KEY, shoe_id INT REFERENCES catalog....
I have 3 tables:
CREATE TABLE catalog.shoes (
    shoe_id SERIAL PRIMARY KEY,
    brand VARCHAR(255) NOT NULL,
    model VARCHAR(255) NOT NULL,
    price INT NOT NULL,
	CONSTRAINT shoe_name UNIQUE (brand, model)
);

CREATE TABLE catalog.stock (
	item_id SERIAL PRIMARY KEY,
    shoe_id INT REFERENCES catalog.shoes(shoe_id) ON DELETE CASCADE,
	color VARCHAR(255) NOT NULL,
    size INT NOT NULL,
	stock_count INT NOT NULL
);

CREATE TABLE catalog.photos (
	shoe_id INT REFERENCES catalog.shoes(shoe_id) ON DELETE CASCADE,
    color VARCHAR(255) NOT NULL,
	photo_url TEXT UNIQUE
);
I have this query to SELECT rows:
SELECT item_id, st.color st_col, p.color p_col, size, stock_count, brand, model, photo_url
FROM catalog.stock st
JOIN catalog.shoes s ON s.shoe_id = st.shoe_id
JOIN catalog.photos p ON p.shoe_id = st.shoe_id
The issue I have is that color from the photos table (p_col) does not correspond with the color from the stock table (st_col). Is there a simple solution which would match those rows with one another on the SELECT query or would it be better to create the relationship when I CREATE the tables? The reason I do not want to refactor my tables too much (unless it is necessary) is because I have struggled to create a relation between the colors in the table definitions because the color is not unique in the photos table. I assumed it would be easier to make them line up when I retrieve the data instead. I'm open to changing my tables, but as you can see, I don't like having too complicated definitions since this is just for a school project. I tried creating a CONSTRAINT in the stock table CONSTRAINT (shoe_id, color) UNIQUE and the photos table FOREIGN KEY (shoe_id, color) REFERENCES catalog.stock (shoe_id, color) but I kept getting syntax errors (I tried different ways, such as giving the constraint a name and referencing that name, etc.). This is an example of returned rows:
item_id	st_col	p_col	size	stock_count	brand	model			photo_url
1000	Black	White	6		11			Adidas	Breaknet 2.0	Image
1000	Black	Black	6		11			Adidas	Breaknet 2.0	Image
1001	Black	White	7		12			Adidas	Breaknet 2.0	Image
1001	Black	Black	7		12			Adidas	Breaknet 2.0	Image
1003	White	White	6		5			Adidas	Breaknet 2.0	Image
1003	White	Black	6		5			Adidas	Breaknet 2.0	Image
Here we can see that I'm getting a row for each p_col value in the photos table, but I only want the p_col from the corresponding st_col. I should only have one row per item_id. This is what I expect:
item_id	st_col	p_col	size	stock_count	brand	model			photo_url
1000	Black	Black	6		11			Adidas	Breaknet 2.0	Image
1001	Black	Black	7		12			Adidas	Breaknet 2.0	Image
1003	White	White	6		5			Adidas	Breaknet 2.0	Image
ntruter42 (121 rep)
Oct 7, 2023, 10:58 PM • Last activity: Oct 8, 2023, 07:12 PM
-1 votes
3 answers
464 views
Given a table containing class and students, need to find the diff in students
I have class_students table where given 2 class ids I need to find the diff in students. This is sql fiddle that I used, http://sqlfiddle.com/#!9/dba48e/11 Any help here.
I have class_students table where given 2 class ids I need to find the diff in students. This is sql fiddle that I used, http://sqlfiddle.com/#!9/dba48e/11 Any help here.
Lokn (99 rep)
Aug 1, 2019, 05:07 AM • Last activity: Sep 9, 2023, 10:02 AM
0 votes
0 answers
37 views
Noobie needs help on designing database for membership management tool
I have searched through some of the database examples, but have yet to wrap my head around the logic of the relations between databases, so appreciate some support. Here is what I am trying to do: for a non-profit organisation (German Kindergarden), I am trying to set up a membership management tool...
I have searched through some of the database examples, but have yet to wrap my head around the logic of the relations between databases, so appreciate some support. Here is what I am trying to do: for a non-profit organisation (German Kindergarden), I am trying to set up a membership management tool/database. Here is what it needs to do: - store member details (name, address, etc): these are usually one or two parents - Record children details: the children in the kindergarden - Provide general information about members and children via queries/reports Provide an overview over memberships: a membership is family based (one family one membership) and can contain one or more members as well as one or more children. The membership shall then record things like the membership fee and if there is a bank account linked already as well as start and end date. I need to be able to enter: - new members - new children - and obviously new memberships. In my view, this should contain 3 tables: | Members | Children | Memberships | |---------|----------|-------------| | MemberID| ChildID | MembershipID| | MembershipID (FK) | MembershipID (FK) | Name | | Last Name |Last Name | Fee | |First Name |First Name| StartDate | |etc.| etc. | EndDate | ||| My idea is to use the "Membership" table to rule them all. The name of the membership should be equal to the family name of the child. (am I missing a relationship here? probably...) Now my questions: - Am I on the right track with the general setup? - If so, how would I go about creating these databases? I am pretty tool agnostic, but would prefer working with pure SQL. MySQL WOrkbench could work too. - How would I 'link' the /name/ of the membership to any of the child's last name? - I have the data for members and children stored already. How do I 'import' them into the tables? I guess it makes sense to first populate 'members' and 'children' and then 'create the 'memberships'? Sorry if this is really basic stuff, but would appreciate some help to point me in the right direction. Cheers, mor3dr3ad
mor3dr3ad (1 rep)
Sep 1, 2023, 12:14 PM
0 votes
1 answers
628 views
What is the most straightforward way to create subtypes and supertypes at the same time?
I hope this isn't too basic a question, but I am hoping that the DB engineers here will help me out. Do relational DBs usually have a straightforward way of doing the following?: 1. Create a supertable with a UUID as the primary key 2. Create several subtables where each have as their primary key th...
I hope this isn't too basic a question, but I am hoping that the DB engineers here will help me out. Do relational DBs usually have a straightforward way of doing the following?: 1. Create a supertable with a UUID as the primary key 2. Create several subtables where each have as their primary key the primary key from the supertable as a foreign key. 3. When I add a row to a subtable, a corresponding row is created in the supertable. Probably by automatically creating the supertable row first before creating a new row in the subtable with it as a foreign key. In my case, I am designing database that will store several types of post (text, video, image). Each (sub)type of post has unique attributes, and thus should get its own table. However, I want all posts to be organized by a GUID in a supertable that contains attributes shared by all post subtypes. I've been able to set up these tables, but I dislike the fact that I cannot enter into a subtable a post of a given subtype and automatically populate the supertable. It's been suggested that I just create both supertable and subtable entries with one command like this:
with new_post as (
  insert into posts (name) values ('My new video post')
  returning id
)
insert into videos (guid)
select id 
from new_post;
However this seems awkward. I know there are lots of ways to set up relations and backfill columns in other tables, yet I cannot seem to find an example of this particular type of backfilling relationship. I happen to be using Postgres via SQLAlchemy, but an answer in general terms about how this problem would be approached in any DB would be welcome.
Logos Masters (3 rep)
Jul 22, 2023, 06:39 PM • Last activity: Jul 23, 2023, 03:56 PM
0 votes
2 answers
385 views
How to join multiple many to many tables
I have tables - games, game_views, game_views_game_links, genres, games_genres_links. I need to count views from game_views, filter by them and join genres table to genres field. If i use only 2 joins with game_views, game_views_game_links i give normal result. My query is give all genres 1 view, ca...
I have tables - games, game_views, game_views_game_links, genres, games_genres_links. I need to count views from game_views, filter by them and join genres table to genres field. If i use only 2 joins with game_views, game_views_game_links i give normal result. My query is give all genres 1 view, can i separate this? **Relations:** - games many to many genres - games one to many game_views this query gives correct result
SELECT "games"."id" AS "id",
	COUNT("game_views"."id") AS "views",
	"games"."created_at",
	"games"."updated_at"
FROM "games"

LEFT JOIN "game_views_game_links" AS "gvgl" ON "games"."id" = "gvgl"."game_id"
LEFT JOIN "game_views" ON "game_views"."id" = "gvgl"."game_view_id"

WHERE "game_views"."created_at" > '2023-03-13T12:00:02+03:00'
GROUP BY "games"."id"
ORDER BY "views" DESC,
	"updated_at" ASC
this query doubled
SELECT "games"."id" AS "id",
	COUNT("game_views"."id") AS "views",
	"games"."created_at",
	"games"."updated_at"
FROM "games"

LEFT JOIN "game_views_game_links" AS "gvgl" ON "games"."id" = "gvgl"."game_id"
LEFT JOIN "game_views" ON "game_views"."id" = "gvgl"."game_view_id"

LEFT JOIN "games_genres_links" AS "ggl" ON "games"."id" = "ggl"."game_id"
LEFT JOIN "genres" ON "genres"."id" = "ggl"."genre_id"

WHERE "game_views"."created_at" > '2023-03-13T12:00:02+03:00'
GROUP BY "games"."id"
ORDER BY "views" DESC,
	"updated_at" ASC
Nark Ebavich (3 rep)
May 14, 2023, 12:35 PM • Last activity: May 14, 2023, 11:09 PM
-1 votes
1 answers
2163 views
Update all rows with a one to many relationship count in the same table in MYSQL
I am trying to update all rows of a MYSQL table with the total amount of referred users for each user. 1 user can refer multiple users and I need to run a MYSQL query to update the invite count (total amount of users they have referred) on all rows. Columns: - id - referred_by_user_id - invite_count...
I am trying to update all rows of a MYSQL table with the total amount of referred users for each user. 1 user can refer multiple users and I need to run a MYSQL query to update the invite count (total amount of users they have referred) on all rows. Columns: - id - referred_by_user_id - invite_count This is what I came up with but it is not working (returns 0 on every row). What is the best way to accomplish this query?
SET @code=0;
UPDATE users
    SET invite_count =
       (SELECT count(*)
           where referred_by_user_id = @code:=@code+1);
Table Schema
CREATE TABLE users (
  id bigint unsigned NOT NULL AUTO_INCREMENT,
  name varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  referred_by_user_id bigint DEFAULT NULL,
  invite_count int NOT NULL DEFAULT '0',
  created_at timestamp NULL DEFAULT NULL,
  updated_at timestamp NULL DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
webmaster8800 (1 rep)
Feb 8, 2022, 03:46 AM • Last activity: Mar 11, 2023, 03:01 PM
1 votes
1 answers
326 views
How to count the number of relationships to a table in MySQL?
I am arranging an ERD diagram of an existing database with about a 100 tables, to add some structure to the process, how rank out the number of relations the tables have to each other? For example, table 1 is related directly to ten tables. Table 2 is related to four tables and so on. I am using MyS...
I am arranging an ERD diagram of an existing database with about a 100 tables, to add some structure to the process, how rank out the number of relations the tables have to each other? For example, table 1 is related directly to ten tables. Table 2 is related to four tables and so on. I am using MySQL workbench and the diagram is drawing using the programs Reverse Engineer on an existing database.
OrigamiEye (135 rep)
Feb 4, 2023, 08:08 AM • Last activity: Feb 5, 2023, 03:28 PM
Showing page 1 of 20 total questions