0

Fairly new to mySQL . Trying to get a query to work, but keep getting the right results, but duplicated.

Here's the query

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) );

I'm totally lost. Any help would be greatly appreciated.

2
  • Yes. See about JOINs. Any beginners book or tutorial would do. Commented Dec 20, 2017 at 8:36
  • I'm surprised that a distinct clause fails to remove duplicates. Can you add sample data to your question as text? Commented Dec 20, 2017 at 8:52

1 Answer 1

1

Joining tables is the way to go, you do not pile all your conditions into the where clause:

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

This way the DB can optimize your query and due to the joins on the tables does not need to scan so much data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.