How do i select the highest number in one column and then search the the id in other table - sql

How do I select the highest number in one column and then search the the ID in other table?
I have these two tables:
create table armazens_has_artigos
(
stockMinimo int not null,
stockQuantidade int not null,
idArtigos int not null,
idArmazens int not null,
idZonasFisicas int not null
constraint fk_armazens_has_artigos_idArtigos
foreign key (idArtigos)
references artigos (idArtigos) on delete cascade,
constraint fk_armazens_has_artigos_idArmazens
foreign key (idArmazens)
references armazens (idArmazens) on delete cascade,
constraint fk_armazens_has_artigos_zonasFisicas_idZonasFisicas
foreign key (idZonasFisicas)
references zonasFisicas (idZonasFisicas) on delete cascade
);
In this one I need to select the highest StockQuantidade and then with the same id select in this table the nome
create table artigos
(
idArtigos int primary key,
nome varchar (45) not null,
descr varchar (45) not null,
precoCompra float not null,
precoVenda float not null,
unidadeRepresentacao varchar (45) not null
);

There might be more then one Artigos matching the criteria:
SELECT *
FROM artigos
WHERE idArtigos IN
(
SELECT idArtigos
FROM dbo.armazens_has_artigos
WHERE stockQuantidade =
(
SELECT MAX(stockQuantidade)FROM armazens_has_artigos
)
);

SELECT
nome
FROM artigos
JOIN armazens_has_artigos
ON armazens_has_artigos.idArtigos = artigos.idArtigos
WHERE armazens_has_artigos.stockQuantidade = (SELECT
MAX(stockQuantidade)
FROM armazens_has_artigos)

Related

Can have in my case foreign key duplicated value?

can have in this case foreign key duplicated value? Or better just have an index on column?
Here is my table structure:
CREATE TABLE customers(
id INT (10) NOT NULL,
name VARCHAR (50) NOT NULL,
city VARCHAR (50) NOT NULL
);
CREATE TABLE orders(
cus_id INT (10) NOT NULL ,
order_date DATETIME NOT NULL
);
CREATE TABLE products(
id INT (5) NOT NULL,
product_name VARCHAR(50) NOT NULL,
product_price INT(10) NOT NULL
);
But in orderitems table (Where I have stored the ordered products, the customer can have multiple products ordered so the foreign key value (cus_id) can be duplicated)
CREATE TABLE ordered_items(
id INT (10) NOT NULL,
cus_id INT (10) NOT NULL,
product_id INT(5) NOT NULL
);
ALTER TABLE customers ADD CONSTRAINT customer_id PRIMARY KEY ( id ) ;
ALTER TABLE orders ADD CONSTRAINT customers_id_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
ALTER TABLE ordered_items ADD CONSTRAINT ordered_items_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
EDIT:
Sorry the ordered_items table have a unique ID column as well.
Yes! you can have multiple value of cus_id inside ordered_items. however, your intention is better served if you replace cus_id by order_id from orders, Thus your relationship would sound like,
a **customer** can have multiple *orders*,
an **order** can have multiple *order items*,
and an **order item** can only have single *product*
your sql would look like this
CREATE TABLE customers(
id INT (10) NOT NULL,
name VARCHAR (50) NOT NULL,
city VARCHAR (50) NOT NULL
);
ALTER TABLE customers ADD CONSTRAINT customer_id PRIMARY KEY ( id ) ;
CREATE TABLE orders(
id INT (5) NOT NULL,
cus_id INT (10) NOT NULL ,
order_date DATETIME NOT NULL
);
ALTER TABLE orders ADD CONSTRAINT order_id PRIMARY KEY ( id ) ;
ALTER TABLE orders ADD CONSTRAINT customers_id_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
CREATE TABLE products(
id INT (5) NOT NULL,
product_name VARCHAR(50) NOT NULL,
product_price DOUBLE NOT NULL
);
ALTER TABLE products ADD CONSTRAINT product_id PRIMARY KEY ( id ) ;
CREATE TABLE ordered_items(
id INT (10) NOT NULL,
order_id INT (10) NOT NULL,
product_id INT(5) NOT NULL
);
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_id PRIMARY KEY ( id ) ;
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_order_frK FOREIGN KEY ( order_id ) REFERENCES orders ( id );
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_prd_frK FOREIGN KEY ( product_id) REFERENCES products ( id );

Address table applied to Users and Stores

On a database I have the following tables:
create table dbo.Stores (
Id int not null
Name nvarchar (120) not null
)
create table dbo.Users (
Id int not null
Name nvarchar (120) not null
)
Each User or Shop can have:
1 - One physical address;
2 - One website or social media addresses.
Should I have tables for Addresses and Social Media. For example:
create table dbo.Addresses (
Id int not null
Street nvarchar (120) not null,
PostalCode nvarchar (12) not null
City nvarchar (40) not null,
Latitude float null,
Longitude float null
)
create table dbo.UserAddresses (
UserId int not null,
AddressId int not null
)
And the same for Social Media, phone numbers and so on ...
Should I just add Columns to the Users table?
Update 1
For website addresses and social media addresses I am considering having the following:
create table dbo.UserWebAddresses (
UserId int not null,
WebAddressTypeId int not null,
Value nvarchar(200) not null
)
create table dbo.WebAddressTypes (
Id int not null,
Name nvarchar(20) not null
)
Does this make sense?
Add those columns directly to dbo.Stores and dbo.Users if there are no duplicated rows. If they might be duplicated, then create a new table and use FKs.
CREATE TABLE dbo.Stores
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL
);
CREATE TABLE dbo.Users
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL
);
CREATE TABLE dbo.Addresses
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Street NVARCHAR(120) NOT NULL,
PostalCode NVARCHAR(12) NOT NULL,
City NVARCHAR(40) NOT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
ALTER TABLE dbo.Stores
ADD CONSTRAINT Stores_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
ALTER TABLE dbo.Users
ADD CONSTRAINT Users_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
We can also go with the following solution as well if I understood everything correct:
CREATE TABLE dbo.Stores
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
CREATE TABLE dbo.Users
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
CREATE TABLE dbo.Addresses
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Street NVARCHAR(120) NOT NULL,
PostalCode NVARCHAR(12) NOT NULL,
City NVARCHAR(40) NOT NULL
);
ALTER TABLE dbo.Stores
ADD CONSTRAINT Stores_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
ALTER TABLE dbo.Users
ADD CONSTRAINT Users_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);

How to Relate 2 table with each other with 2 foreign keys

Here is my code it generates Foreign key conflict error
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NOT NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NOT NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
You cannot do that. This is a circular reference.
This is a bad design but if you want to do that, you need to make foreign key columns Nullable.
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
Then you need to update reference fields after inserting records in tblBatches and tblProducts.
The good design says you need to create a bridge table like this:
CREATE TABLE tblProductsBatch
(
ID int NOT NULL IDENTITY PRIMARY KEY,
ProductID int NOT NULL,
BatchID int NOT NULL
)
And after inserting product and batch, you need to insert a record in this table to link rows to each other.

SQL error 150 on table creation

I know the error 150 is related to foreign keys, but i can't figure out what wrong here.
CREATE TABLE IF NOT EXISTS User(
id_user INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
nom VARCHAR(255) NOT NULL,
prenom VARCHAR(255) NOT NULL,
naissance DATE NOT NULL,
email VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS Livre(
id_livre INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
titre VARCHAR(255) NOT NULL,
parution DATE NOT NULL,
id_edit INT NOT NULL,
id_user INT NOT NULL,
FOREIGN KEY ( id_edit)
REFERENCES Editeur(id_edit)
ON DELETE CASCADE,
FOREIGN KEY ( id_user)
REFERENCES User(id_user)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS Publication(
id_pub INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
texte TEXT NOT NULL,
date_pub DATE NOT NULL,
titre_pub VARCHAR(255) NOT NULL,
id_livre INT NOT NULL,
id_user INT NOT NULL,
FOREIGN KEY ( id_user)
REFERENCES User(id_user)
ON DELETE CASCADE,
FOREIGN KEY (id_livre)
REFERENCES Livre(id_livre)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS Editeur(
id_edit INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
pays VARCHAR(255) NOT NULL,
adresse VARCHAR(255) NOT NULL,
tel VARCHAR(255) NOT NULL
);
The error occurs when i try to create tables Livre and Publication.
Types are the same so it doesn't seem to be the problem.
By mindful of the order in which you create the tables.
For instance, your table creation statement for Livre defines a foreign key on Editeur. But the table Editeur has not been created yet.
Adjust the create table statement ordering as required.

INSERT statements gives me different errors

I'm trying to run a file which contains INSERT statements. The statements will either give me an not enough values error or unique constraint error.
Below is my create table statement:
CREATE TABLE PART
(PNum VARCHAR(25) NOT NULL,
PName VARCHAR(75) NOT NULL,
PUnitPrice NUMBER(7,2) NOT NULL,
ComponentOf VARCHAR(25),
CONSTRAINT PART_PKEY PRIMARY KEY(PNum),
CONSTRAINT PART_FKEY FOREIGN KEY(ComponentOf)
REFERENCES PART(PNum)
};
CREATE TABLE MANUFACTURER
(MName VARCHAR(50) NOT NULL,
MAddress VARCHAR(100) NOT NULL,
MPhone VARCHAR(25) NOT NULL,
CONSTRAINT MANUFACTURER_PKEY PRIMARY KEY(MName),
);
CREATE TABLE PART-MANUFACTURED
(MDate DATE,not null
PNum VARCHAR(25) NOT NULL,
MName VARCHAR(50) NOT NULL,
Quantity NUMBER(10) NOT NULL,
CONSTRAINT PART-MANUFACTURED_PKEY PRIMARY KEY(MName,PNum,MDate),
CONSTRAINT PART-MANUFACTURED_FKEY1 FOREIGN KEY(PNum)
REFERENCES PART(PNum),
CONSTRAINT PART-MANUFACTURED_FKEY2 FOREIGN KEY(MName)
REFERENCES MANUFACTURER(MName)
);
CREATE TABLE CUSTOMER
(CNum VARCHAR(25) NOT NULL,
CName VARCHAR(75) NOT NULL,
CType VARCHAR(20) NOT NULL,
CONSTRAINT CUSTOMER_PKEY PRIMARY KEY(CNum),
CONSTRAINT CHECK_CType
CHECK(CType IN (‘INDIVIDUAL,’INSTITUITION’))
);
CREATE TABLE ORDERS
(CNum VARCHAR(25) NOT NULL,
PNum VARCHAR(25) NOT NULL,
OrderDate DATE NOT NULL,
OrderQuantity NUMBER(7,2) NOT NULL,
CONSTRAINT ORDERS_PKEY PRIMARY KEY(CNum,PNum,OrderDate),
CONSTRAINT ORDERS_FKEY1 FOREIGN KEY(CNum)
REFERENCES CUSTOMER(CNum),
CONSTRAINT ORDERS_FKEY2 FOREIGN KEY(PNum)
REFERENCES PART(PNum)
);
Below is the statement that gives me the not enough values error:
INSERT INTO PART
VALUES('S001','System-Economy',1100,null);
INSERT INTO PART
VALUES('M001','Monitor-17 inch',250,'S001');
For the unique constraints error, I believe i have to insert the data in order of their primary and referencing keys right?
So what do I need to change in order for the the insert statements to work?
I dont see any error on Insert. The problem is with your create table. Plenty to correct. Try this
CREATE TABLE PART ( PNUM VARCHAR ( 25 ) NOT NULL,
PNAME VARCHAR ( 75 ) NOT NULL,
PUNITPRICE NUMBER ( 7, 2 ) NOT NULL,
COMPONENTOF VARCHAR ( 25 ),
CONSTRAINT PART_PKEY PRIMARY KEY ( PNUM ),
CONSTRAINT PART_FKEY FOREIGN KEY
( COMPONENTOF )
REFERENCES PART ( PNUM ) );
CREATE TABLE MANUFACTURER ( MNAME VARCHAR ( 50 ) NOT NULL,
MADDRESS VARCHAR ( 100 ) NOT NULL,
MPHONE VARCHAR ( 25 ) NOT NULL,
CONSTRAINT MANUFACTURER_PKEY PRIMARY KEY ( MNAME ) );
CREATE TABLE PART_MANUFACTURED ( MDATE DATE NOT NULL,
PNUM VARCHAR ( 25 ) NOT NULL,
MNAME VARCHAR ( 50 ) NOT NULL,
QUANTITY NUMBER ( 10 ) NOT NULL,
CONSTRAINT PART_MANUFACTURED_PKEY PRIMARY KEY
( MNAME, PNUM, MDATE ),
CONSTRAINT PART_MANUFACTURED_FKEY1 FOREIGN KEY
( PNUM )
REFERENCES PART ( PNUM ),
CONSTRAINT PART_MANUFACTURED_FKEY2 FOREIGN KEY
( MNAME )
REFERENCES MANUFACTURER ( MNAME ) );
CREATE TABLE CUSTOMER ( CNUM VARCHAR ( 25 ) NOT NULL,
CNAME VARCHAR ( 75 ) NOT NULL,
CTYPE VARCHAR ( 20 ) NOT NULL,
CONSTRAINT CUSTOMER_PKEY PRIMARY KEY ( CNUM ),
CONSTRAINT CHECK_CTYPE CHECK
( CTYPE IN ('INDIVIDUAL', 'INSTITUITION') ) );
CREATE TABLE ORDERS ( CNUM VARCHAR ( 25 ) NOT NULL,
PNUM VARCHAR ( 25 ) NOT NULL,
ORDERDATE DATE NOT NULL,
ORDERQUANTITY NUMBER ( 7, 2 ) NOT NULL,
CONSTRAINT ORDERS_PKEY PRIMARY KEY
( CNUM, PNUM, ORDERDATE ),
CONSTRAINT ORDERS_FKEY1 FOREIGN KEY
( CNUM )
REFERENCES CUSTOMER ( CNUM ),
CONSTRAINT ORDERS_FKEY2 FOREIGN KEY
( PNUM )
REFERENCES PART ( PNUM ) );
INSERT INTO
PART
VALUES
( 'S001',
'System-Economy',
1100,
NULL );
INSERT INTO
PART
VALUES
( 'M001',
'Monitor-17 inch',
250,
'S001' );