postgresql display products that were ordered - postgresql

i havе tables like this and i need to display products that were ordered
create table customer (
id int primary key,
first_name varchar(100) not null,
last_name varchar(100) not null,
city varchar(100) null,
country varchar(100) null,
phone varchar(100) null
);
create table supplier (
id int primary key,
company_name varchar(100) not null,
contact_name varchar(100) null,
contact_title varchar(100) null,
city varchar(100) null,
country varchar(100) null,
phone varchar(100) null,
fax varchar(100) null
);
create table product (
id int primary key,
product_name varchar(100) not null,
unit_price decimal(12,2) null default 0,
package varchar(100) null,
is_discontinued boolean not null default false,
supplier_id int references supplier(id) not null
);
create table orders (
id int primary key,
order_date timestamp not null default now(),
order_number varchar(100) null,
total_amount decimal(12,2) null default 0,
customer_id int references customer(id) not null
);
create table order_item (
id int primary key,
unit_price decimal(12,2) not null default 0,
quantity int not null default 1,
order_id int references orders(id) not null,
product_id int references product(id) not null
);

If you only need product_name of products that were ordered, you can do the below sql. It involves only 2 tables.
select distinct p.product_name
from order_item o
join product p
on o.product_id = p.id
Postgres DB Fiddle

Related

I can't create this PostgreSQL Query: Grouping by a different condition to the "order by" condition

I need to order my query in a different way i need to group my tables. I need to count how many men are in every department, but organize the query by quantity of people (Not only men, but also women) in every department, in descending way.
This is the diagram and the code of the tables:
Relational model of the tables
CREATE SCHEMA Academico;
CREATE TABLE Academico.PAIS(
ID int NOT NULL,
NOMBRE varchar(30) NOT NULL,
DESCRIPCION varchar(120) NULL,
CONSTRAINT PK_PAIS PRIMARY KEY (ID));
CREATE TABLE Academico.DEPARTAMENTO(
ID int NOT NULL,
NOMBRE varchar(30) NOT NULL,
CODIGO int NOT NULL,
DESCRIPCION varchar(120) NULL,
IDPAIS int NOT NULL,
CONSTRAINT PK_DEPARTAMENTO PRIMARY KEY (ID));
CREATE TABLE Academico.CIUDAD(
ID int NOT NULL,
NOMBRE varchar(255) NOT NULL,
CODIGO int NOT NULL,
DESCRIPCION varchar(120) NULL,
IDDEPARTAMENTO int NOT NULL,
CONSTRAINT PK_CIUDAD PRIMARY KEY (ID));
ALTER TABLE Academico.DEPARTAMENTO
ADD CONSTRAINT FK_DEPARTAMENTO_PAIS FOREIGN KEY(IDPAIS)
REFERENCES Academico.PAIS (ID)
on delete restrict on update restrict;
ALTER TABLE Academico.CIUDAD
ADD CONSTRAINT FK_CIUDAD_DEPARTAMENTO FOREIGN KEY(IDDEPARTAMENTO)
REFERENCES Academico.DEPARTAMENTO (ID)
on delete restrict on update restrict;
CREATE TABLE Academico.SEXO(
ID int NOT NULL,
NOMBRE varchar(30) NOT NULL,
DESCRIPCION varchar(120) NULL,
CONSTRAINT PK_SEXO PRIMARY KEY (ID));
CREATE TABLE Academico.TIPODOCUMENTO(
ID int NOT NULL,
NOMBRE varchar(30) NOT NULL,
DESCRIPCION varchar(120) NULL,
CONSTRAINT PK_TIPODOCUMENTO PRIMARY KEY (ID));
CREATE TABLE Academico.PERSONA(
ID int NOT NULL,
NOMBRE varchar(10) NOT NULL,
APELLIDO varchar(30) NOT NULL,
IDSEXO int NOT NULL REFERENCES Academico.SEXO(id),
IDCIUDAD int NOT NULL REFERENCES Academico.CIUDAD(id),
DOCUMENTO varchar(50) NOT NULL,
IDTIPODOCUMENTO int NOT NULL REFERENCES Academico.TIPODOCUMENTO(id),
FECHANACIMIENTO date NULL CHECK (FECHANACIMIENTO > '1900-01-01'),
FEvarcharEGISTRO date NOT NULL DEFAULT Now() ,
email varchar (355) UNIQUE NOT NULL,
PROFESION varchar(12) NULL,
PERFIL varchar(120) NULL,
CONSTRAINT PK_PERSONA PRIMARY KEY
(ID) );
I tried this two querys that give me the expected results but in a separated way:
select
d.nombre as _departamento, s.nombre as sex, count(1) as total_sexo
from
academico.persona p, academico.sexo s,
academico.ciudad c, academico.departamento d
where
p.idsexo = s.id
and p.idciudad = c.id
and c.iddepartamento = d.id
and upper( s.nombre ) = 'MASCULINO'
group by
d.id,
s.id
order by
d.nombre
-- =======================================================
-- I don't know how to "merge" these two into one query
-- =======================================================
select
d.nombre as _departamento, count(1) as total_gente
from
academico.persona p, academico.ciudad c,
academico.departamento d, academico.sexo s
where
p.idciudad = c.id
and c.iddepartamento = d.id
and p.idsexo = s.id
group by
d.id
order by
total_gente desc
;
I need to get those results with only one query
This is the perfect use for the FILTER (WHERE...) construct.
...
count(1) as total_gente,
count(1) filter (where upper( s.nombre ) = 'MASCULINO') as total_masculino
...
And then take the upper( s.nombre ) = 'MASCULINO' out of the main where clause.

MySQL Workbench - Cant select FK column. Dropdown not populating

Here are my tables CREATE Statements:
CREATE TABLE `User` (
`UserId` int NOT NULL AUTO_INCREMENT,
`CompanyId` int NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`UserName` varchar(100) NOT NULL,
PRIMARY KEY (`UserId`),
KEY `FK_Company_User_idx` (`CompanyId`),
CONSTRAINT `FK_Company_User` FOREIGN KEY (`CompanyId`) REFERENCES `Company` (`CompanyId`)
) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `Notification` (
`NotificationId` int NOT NULL AUTO_INCREMENT,
`Email` varchar(100) DEFAULT NULL,
`Message` text,
`Subject` varchar(100) DEFAULT NULL,
`UserId` int NOT NULL,
PRIMARY KEY (`NotificationId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I am trying to create a FK between UserId in Notification and UserId in User but the dropdown for selecting the field is not populating.
Any help is appreciated.

PostgreSQL gives syntax error at "foreign" or near

These are tables before referances
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) SERIAL PRIMARY KEY autoincrement,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
After creating this tables I want to create this table
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES time(idtime)
));
But I get error as
"ERROR: syntax error at or near "REFERENCES"
LINE 9: FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustom..."
Thanks in advance
The idcustomer from olap.fact and idcustomer from olap.customers has different datatype SERIAL and Varchar(10),
I have corrected the datatypes and validated the code below
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer) REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES olap.time(idtime)
);

postgresql cannot insert data to newly added column

In postgresql I have a table which I need to add a new column. the original table ddl is belowing:
CREATE TABLE survey.survey_response (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
CONSTRAINT survey_response_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
) ;
Then I alter the table to add a new column:
alter table survey.survey_response add column system_tags varchar(30) ;
But after that I found my instert statement cannot make change to this new column, for all the original columns it works fine:
INSERT INTO survey.survey_response
(id, survey_id, user_id, tags, system_tags)
VALUES(uuid_generate_v4(), uuid_generate_v4(),'1123','dsfsd', 'dsfsd');
select * from survey.survey_response where user_id = '1123';
The "tags" columns contains inserted value, however, system_tags keeps null.
I tested the above scenario in my local postgreSQL 9.6, any ideas about this strange behavior? Thanks a lot
-----------------update----------
I found this survey.survey_response table has been partitioning based on month, So my inserted record will also be displayed in survey.survey_response_y2017m12. but the new system_tags column is also NULL
CREATE TABLE survey.survey_response_y2017m12 (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
system_tags varchar(30) NULL,
CONSTRAINT survey_response_y2017m12_response_date_check CHECK (((response_date >= '2017-12-01'::date) AND (response_date < '2018-01-01'::date)))
)
INHERITS (survey.survey_response)
WITH (
OIDS=FALSE
) ;
If I run the same scenario in a non-partition table then the insert works fine.
So do I need any special settings for alter table for partition table?
Old thread but you need to drop and create again the RULE to fix the issue.

Multi-table query - get friend updates

SELECT M.msg_id, M.uid_fk, M.message, M.created,
U.fname, U.lname, M.uploads
FROM messages M, users_friends F, users U
WHERE M.uid_fk=F.friendID
and F.userID = '5'
and status='2'
Building a facebook-like wall and want to grab messages(updates) from friends.
The query above returns an empty set, even though I've made sure there are messages from user 5 in the table.
Schema:
CREATE TABLE IF NOT EXISTS `messages` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`message` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
`uid_fk` int(11) DEFAULT NULL,
`ip` varchar(30) DEFAULT NULL,
`created` int(11) DEFAULT '1269249260',
`uploads` varchar(30) DEFAULT NULL,
PRIMARY KEY (`msg_id`),
KEY `uid_fk` (`uid_fk`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=263 ;
CREATE TABLE IF NOT EXISTS `users` (
`fname` varchar(15) NOT NULL,
`lname` varchar(15) NOT NULL,
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(23) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`DOB` date DEFAULT NULL,
`sex` varchar(1) DEFAULT NULL,
`about` text NOT NULL,
`location` varchar(20) DEFAULT NULL,
`last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_level` int(11) NOT NULL DEFAULT '0',
`profile_image` varchar(200) NOT NULL,
`profile_image_small` varchar(200) NOT NULL,
PRIMARY KEY (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;
CREATE TABLE IF NOT EXISTS `users_friends` (
`userID` int(11) NOT NULL,
`friendID` int(11) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`userID`,`friendID`),
KEY `fk_users_has_friends_users1` (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You are single quoting your INT values in the WHERE clause → '5' & '2'.
Also, try JOINs.
SELECT M.msg_id,
M.uid_fk,
M.message,
M.created,
U.fname,
U.lname,
M.uploads
FROM messages M
INNER JOIN users_friends F ON F.friendID = M.uid_fk
AND F.userID = 5
AND F.status = 2
INNER JOIN users U ON U.userID = F.friendID;