SQL INTERSECT查询

时间:2013-07-26 08:45:45

标签: mysql sql

我想显示包含相关列的表格。例如,有3个表(department,dept_emp和employees)。如果我只对dept_no感兴趣,我的查询应返回department和dept_emp表。但是,如果我对dept_no和emp_no感兴趣,结果应该只是dept_emp表。

所以我想出了这个查询,但显然存在语法错误。我可以知道是否还有其他选择吗?

(SELECT TABLE_NAME
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE COLUMN_NAME = 'dept_no')
INTERSECT
(SELECT TABLE_NAME
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE COLUMN_NAME = 'empt_no')

2 个答案:

答案 0 :(得分:2)

只要您使用MySql,就可以通过子查询来完成:

    SELECT DISTINCT TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME = 'dept_no' AND TABLE_NAME IN (SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME = 'empt_no')

答案 1 :(得分:1)

尝试:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
 WHERE COLUMN_NAME = 'dept_no'
INTERSECT
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'empt_no'