Translating INTERSECT statement to MySQL
I have the following query using INTERSECT and I can't figure out how to t开发者_运维问答ranslate it to 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 anyone give me a hand?
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 might need to use SELECT DISTINCT
but I can't tell because I don't know your table structure, unique constraints, etc.
Re your cryptic 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');
The output is this:
+----------------------+----------+
| Title | Variable |
+----------------------+----------+
| A Tale of Two Cities | variable |
+----------------------+----------+
精彩评论