MySQL 查询返回重复结果

标签 mysql sql database

对 mySQL 来说还很陌生。尝试让查询正常工作,但不断获得正确的结果,但结果重复。

这是查询

SELECT DISTINCT 
    band.band_name, concert.venue_name 
FROM 
    band, concert 
WHERE 
    concert.date="2012-10-17" AND band_name 
IN 
    (SELECT band.band_name FROM band WHERE band.band_id 
IN 
    (SELECT tour.band_id from tour where tour.tour_name 
IN 
    (SELECT tour_name from concert where concert.date="2012-10-17")));

DDL:

CREATE TABLE band (
    band_id      INT,
    band_name    VARCHAR(50),
    genre        VARCHAR(20),
    PRIMARY KEY (band_id) );

CREATE TABLE musician (
    person_id   INT,
    name        VARCHAR(50),
    band_id     INT, 
    PRIMARY KEY (person_id),
    FOREIGN KEY (band_id) REFERENCES band(band_id) );

CREATE TABLE tour(
    tour_name   VARCHAR(50),
    band_id     INT,
    PRIMARY KEY (tour_name),
    FOREIGN KEY (band_id) REFERENCES band(band_id) );

CREATE TABLE venue(
    venue_name  VARCHAR(30),
    hire_cost   INT,
    PRIMARY KEY (venue_name) );

CREATE TABLE concert(
    concert_id       INT,
    date             DATE,
    tour_name        VARCHAR(50),
    venue_name       VARCHAR(30),
    ticket_sales     INT, 
    PRIMARY KEY      (concert_id),
    FOREIGN KEY      (tour_name) REFERENCES tour(tour_name),
    FOREIGN KEY      (venue_name) REFERENCES venue(venue_name) );

我完全迷路了。任何帮助将不胜感激。

最佳答案

连接表是正确的方法,您不必将所有条件都堆放在 where 子句中:

SELECT DISTINCT 
    b.band_name, c.venue_name 
FROM concert c 
  join venue v on v.venue_name = c.venue_name -- thats how those 2 tables connect
  join tour t on t.tour_name = c.tour_name    -- thats how those 2 tables connect
  join band b on b.band_id = t.band_id        -- thats how those 2 tables connect
WHERE c.date="2012-10-17"             -- and this gives you all the bandnames and  
                            -- venuenames that play on every concert on this date

这样数据库就可以优化您的查询,并且由于表上的联接不需要扫描这么多数据。

关于MySQL 查询返回重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47900148/

相关文章:

database - 如何将 Gmail 信任的 CA 证书添加到 Oracle Wallet 中?

php - MySQL存储过程使用多个参数

mysql 首先执行 mysql order by

mysql - 类似于中等表(约 3m 条记录)上的查询性能

c# - 用于在 C# 中解析 SQL 查询的正则表达式

可以在 sql profiler 中读取的 SQL 'comment'

mysql - 数据库构建过程管理

php - 使两个表中的同一列始终具有相同的数据?

mysql - 如何在mysql的删除/更新查询中使用子查询

php - 如果在 php mysql 中存在其他插入,如何更新