MySQL如何返回这两个查询的UNION?

时间:2010-10-23 09:48:56

标签: mysql

如何获得这两个查询的UNION:

SELECT dom,sub FROM table WHERE table.dom = X OR table.sub = X

SELECT dom,sub FROM table WHERE table.dom = Y OR table.sub = Y

dom和sub是整数,两个查询都返回一组整数,那么你如何得到这两个集的并集?

任何帮助表示赞赏......

3 个答案:

答案 0 :(得分:5)

你有一个使用UNION的答案,但为什么不只是

SELECT dom,sub FROM table 
  WHERE table.dom = X OR table.sub = X OR table.dom = Y OR table.sub = Y

SELECT dom,sub FROM table 
  WHERE table.dom in (X,Y)  OR table.sub in (X,Y)

(假设您确实在两个查询中讨论同一个表)?

答案 1 :(得分:3)

SELECT dom,sub FROM table WHERE table.dom = X OR table.sub = X
UNION
SELECT dom,sub FROM table WHERE table.dom = Y OR table.sub = Y

...

答案 2 :(得分:1)

以下查询将删除类似的记录,即仅显示不同的

SELECT dom,sub FROM table WHERE table.dom = X OR table.sub = X
UNION
SELECT dom,sub FROM table WHERE table.dom = Y OR table.sub = Y

如果您想要所有记录,请使用

SELECT dom,sub FROM table WHERE table.dom = X OR table.sub = X
UNION ALL
SELECT dom,sub FROM table WHERE table.dom = Y OR table.sub = Y