4

我有以下使用 INTERSECT 的查询,但我不知道如何使用 INNER JOIN 将其转换为 MySQL。

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'

谁能帮我一把?

4

1 回答 1

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

您可能需要使用SELECT DISTINCT,但我不知道,因为我不知道您的表结构、唯一约束等。


回复您的神秘评论:我在测试数据库中尝试了以下脚本:

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

输出是这样的:

+----------------------+----------+
| Title                | Variable |
+----------------------+----------+
| A Tale of Two Cities | variable |
+----------------------+----------+
于 2010-01-05T01:53:12.523 回答