一尘不染

MySql数据库结构:基于单列和不同值的搜索

sql

我需要创建一个数据库,但是没有得到正确的逻辑。

这就像一个故事,但我没有其他方法可以解释它。

场景是:有三个实体。CityBooksLibrary

我必须执行一个任务,在该任务中,我将获取CityId和数组BookIds作为输入,并且必须LibraryNames根据以下条件抛出:

  1. Library应该是给定的City
  2. Library应具有的所有书籍。

我有两个输入类型,第一个用于City(它将为我提供一个CityNameCityId),第二个用于Books(将提供一个由多个BookIds或多个组成的数组BookNames)。

如果很难理解,请与我讨论,我将尽力弄清这个概念。

这是我的严重关切。


阅读 141

收藏
2021-05-16

共1个答案

一尘不染

试试这个:

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

编辑:或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
2021-05-16