如何使用SQL UNION操作

时间:2014-06-14 12:43:13

标签: sql union union-all

  SELECT a.*

  FROM tableA AS a

  LEFT JOIN tableC AS c
  ON c.id = a.catid

  LEFT JOIN tableD AS d
  ON d.id = a.created_by

  INNER JOIN tableE AS e
  ON e.content_id = a.id

  WHERE a.access IN (1,1,5)
  AND c.access IN (1,1,5)

我正在尝试在SQL中使用UNION ALL / UNION操作而不是IN操作。我有麻烦弄清楚如何将上述查询转换为使用UNION。如何将上述查询转换为使用UNION

1 个答案:

答案 0 :(得分:0)

也许你需要这样的东西:

(
SELECT a.*
FROM tableA AS a
LEFT JOIN tableC AS c
ON c.id = a.catid
WHERE a.access = 1
AND c.access = 1
)

UNION ALL

(
SELECT a.*
FROM tableA AS a
LEFT JOIN tableC AS c
ON c.id = a.catid
WHERE a.access = 5
AND c.access = 5
)

UNION ALL

(
SELECT a.*
FROM tableA AS a
LEFT JOIN tableD AS d
ON d.id = a.created_by
INNER JOIN tableE AS e
ON e.content_id = a.id
)