Translation of an INTERSECT statement in MySQL

I have the following query using INTERSECT, and I cannot figure out how to translate it into MySQL using INNER JOIN.

SELECT DISTINCT Title, Variable FROM Table WHERE Location='Location1' AND Date='Date1'  
INTERSECT  
SELECT DISTINCT Title, Variable FROM Table WHERE Location='Location2' AND Date='Date2'  
INTERSECT  
SELECT DISTINCT Title, Variable FROM Table WHERE Location='Location3' AND Date='Date3'

Can anybody help me?

+3
source share
1 answer
SELECT t1.Title, t1.Variable
FROM Table t1
JOIN Table t2 USING (Title, Variable)
JOIN Table t3 USING (Title, Variable)
WHERE (t1.Location, t1.Date) = ('Location1', 'Date1')
  AND (t2.Location, t2.Date) = ('Location2', 'Date2')
  AND (t3.Location, t3.Date) = ('Location3', 'Date3');

You may need to use SELECT DISTINCT, but I can’t say, because I don’t know your table structure, unique restrictions, etc.


Repeat your critical comment: I tried the following script in my test database:

DROP TABLE IF EXISTS MyTable;
CREATE TABLE MyTable (
 id       SERIAL PRIMARY KEY,
 title    VARCHAR(20) NOT NULL,
 variable VARCHAR(20) NOT NULL,
 location VARCHAR(20) NOT NULL,
 date     DATE NOT NULL
);

INSERT INTO MyTable VALUES
 (DEFAULT, 'A Tale of Two Cities', 'variable', 'America', '2010-01-01'),
 (DEFAULT, 'A Tale of Two Cities', 'variable', 'England', '2010-02-01'),
 (DEFAULT, 'A Tale of Two Cities', 'variable', 'France',  '2010-03-01');

SELECT t1.Title, t1.Variable
FROM MyTable t1
JOIN MyTable t2 USING (Title, Variable)
JOIN MyTable t3 USING (Title, Variable)
WHERE (t1.Location, t1.Date) = ('America', '2010-01-01')
  AND (t2.Location, t2.Date) = ('England', '2010-02-01')
  AND (t3.Location, t3.Date) = ('France',  '2010-03-01');

Output:

+----------------------+----------+
| Title                | Variable |
+----------------------+----------+
| A Tale of Two Cities | variable |
+----------------------+----------+
+5
source

Source: https://habr.com/ru/post/1727313/


All Articles