将INTERSECT语句翻译成MySQL

时间:2010-01-05 01:45:28

标签: mysql sql sql-match-all

我使用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'

任何人都可以帮我一把吗?

1 个答案:

答案 0 :(得分: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 |
+----------------------+----------+