I need to create a database but I'm not getting the correct logic.
It's like a story but I don't have any other way to explain it.
The scene is: There are three entities; City
, Books
and Library
.
I have to perform a task in which I will get CityId
and Array of BookIds
as input and I have to throw the LibraryNames
based on following criteria:
Library
should be in the given City
.Library
should have all the books.I have two input types First for City
(It will Provide me a single CityName
or CityId
) and Second is for Books
(It will provide an array which consists of multiple BookIds
or multiple BookNames
).
If it is hard to understand then please discuss with me I will try to clear the concept.
It is a serious concern of me.
try this:
create table City
(
Id int,
Name varchar(50)
);
insert into City (Id, Name)
VALUES
(1, 'Toronto'),
(2, 'Chicago')
create table Libraries(
Id int,
Name varchar(50),
CityId int
);
insert into Libraries (Id, Name, CityId)
VALUES
(1, 'Toronto Library 1', 1),
(2, 'Toronto Library 2', 1),
(3, 'Chicago Library 1', 2),
(4, 'Chicago Library 2', 2)
create table Books(
Id int,
Isbn varchar(12),
LibraryId int
);
insert into Books (Id, Isbn, LibraryId)
Values
(1, '1234567891', 1),
(2, '13344555', 1),
(3, 'x123sada', 1),
(4, 'xasdsadas', 2),
(5, 'axxzksda', 2)
select DISTINCT b.Name
from Books a
inner join Libraries b
on a.LibraryId = b.Id
where Isbn in ('1234567891', '13344555')
and b.CityId = 1
Edit: or 4NF:
create table City
(
Id int,
Name varchar(50)
);
insert into City (Id, Name)
VALUES
(1, 'Toronto'),
(2, 'Chicago')
create table Libraries(
Id int,
Name varchar(50),
CityId int
);
insert into Libraries (Id, Name, CityId)
VALUES
(1, 'Toronto Library 1', 1),
(2, 'Toronto Library 2', 1),
(3, 'Chicago Library 1', 2),
(4, 'Chicago Library 2', 2)
create table Books(
Id int,
Isbn varchar(12),
);
insert into Books (Id, Isbn)
Values
(1, '1234567891'),
(2, '13344555'),
(3, 'x123sada'),
(4, 'xasdsadas'),
(5, 'axxzksda')
create table LibraryBooks
(
LibraryId int,
BookId int
);
insert into LibraryBooks (LibraryId, BookId)
VALUES
(1, 1),
(1, 2),
(3, 1),
(2, 4),
(5, 2)
select DISTINCT c.Name
from Books a
inner join LibraryBooks b
on a.Id = b.BookId
inner join Libraries c on
c.Id = b.LibraryId
where Isbn in ('1234567891', '13344555')
and c.CityId = 1
You could structure it like this: (Three tables)
City:
Id, Name
Id
= unique number
Library:
Id, Name, LiesInCity
Id
= unique numberLiesInCity
= The city Id
the library lies in.
Book:
Id, Name, LiesInLibrary
Id
= numberLiesInLibrary
= The library Id
the book is in.
Then you would SELECT
the book list you had, and check if they are all in that Library
. (You would also check if the Library
is in the right City
)
Note: You would need to have multiple Book
entries if a book is in multiple Library
's