以他们的价格获得门票

时间:2015-11-30 21:05:43

标签: mysql

我想要获得此查询,但我认为所有连接和子查询都让我感到困惑,并且它使用了我数据库中的每个表。

CREATE TABLE Zone(
    name char(12) not null, 
    price_multiplier float not null default 1.0, 
    primary key (name)
    );

CREATE TABLE Seat(
    row_no char(3) not null, 
    zone_name char(12) not null, 
    primary key (row_no), 
    foreign key (zone_name) 
        references Zone(name)
    );

CREATE TABLE Production(
    title varchar(100) not null, 
    url varchar(30) not null unique, 
    base_price numeric(5,2) not null, 
    mins smallint default 90,
    genre varchar(30), 
    description text,  
    primary key (title)
    );

CREATE TABLE Performance(
    id mediumint not null AUTO_INCREMENT,
    date_time datetime not null unique,
    title varchar(100) not null, 
    primary key (id), 
    foreign key (title) 
        references Production(title)
    );

CREATE TABLE Booking(
    ticket_no mediumint not null AUTO_INCREMENT, 
    row_no char(3) not null, 
    performance_id mediumint not null, 
    customer_name varchar(300) not null, 
    primary key (ticket_no), 
    foreign key (row_no) 
        references Seat(row_no), 
    foreign key (performance_id) 
        references Performance(id)
    );

如果我运行此查询,我可以获取已预订的座位,其中包含所有信息:

SELECT 
    b.customer_name, 
    b.row_no, 
    s.zone_name, 
    ROUND(P.base_price * z.price_multiplier, 2) as ticket_price,
    p.title,
    p.date_time
FROM
    Seat s
    JOIN Booking b
        ON s.row_no = b.row_no
    JOIN Performance p
        ON p.id = b.performance_id
    JOIN Production P
        ON p.title = P.title
    JOIN Zone z
        ON z.name = s.zone_name
WHERE
    s.row_no IN 
        (
            SELECT 
                b.row_no 
            FROM 
                Booking b 
            WHERE 
                b.performance_id = :perfID
        )
;

我想通了

SELECT 
    s.row_no,
    s.zone_name,
    ROUND(z.price_multiplier *
        (
            SELECT
                P.base_price
            FROM
                Production P 
                JOIN Performance p
                    ON P.title = p.title
            WHERE
                p.id = :perfID
        )
        , 2) as price
FROM
    Seat s
    JOIN Zone z
        ON s.zone_name = z.name
WHERE
    s.row_no NOT IN 
        (
            SELECT 
                s.row_no
            FROM
                Seat s
                JOIN Booking b 
                    ON s.row_no = b.row_no
            WHERE
                b.performance_id = :perfID
        )

感谢您的帮助。

0 个答案:

没有答案