query with union

Monjoie Dominique asked on April 27, 2018 23:11

Hi,

I have a single query that works well through a filter. Here is it : SELECT custom_Qui.QuiID, custom_SB_quoi.NumQui, custom_Qui.CP, custom_Qui.Latitude, custom_Qui.Longitude FROM custom_Qui, custom_SB_quoi WHERE custom_Qui.QuiID = custom_SB_quoi.NumQui AND ##WHERE## ORDER BY ##ORDERBY##

I create another one with an UNION. When I run it with SQL Manager, I have the correct results. The display of my list ik OK but when I try to apply a filter, I have always the same message : Incorrect syntax near AND. I try to put brackets but anything changes.

Here is the query with problems :

(select custom_qui.QuiID, custom_sb_quoi.numqui, custom_sb_quoi.CPAct1 AS CP, custom_SB_quoi.Latitude_act AS Latitude, custom_SB_quoi.Longitude_act AS Longitude from custom_qui, custom_sb_quoi where custom_qui.quiID = custom_sb_quoi.numqui and CPAct1 is not null

union all

select custom_qui.QuiID, custom_sb_quoi.numqui, custom_qui.CP AS CP, custom_qui.Latitude AS Latitude, custom_qui.Longitude AS Longitude from custom_qui, custom_sb_quoi where custom_qui.quiID = custom_sb_quoi.numqui and CPAct1 is null) AND ##WHERE## ORDER BY ##ORDERBY##

Can anyone help me to solve this ? Thanks.

Correct Answer

Peter Mogilnitski answered on April 28, 2018 13:02

You can use Common Table Expression

WITH myUnion as
(SELECT
  custom_qui.QuiID,
  custom_sb_quoi.numqui,
  custom_sb_quoi.CPAct1 AS CP,
  custom_SB_quoi.Latitude_act AS Latitude,
  custom_SB_quoi.Longitude_act AS Longitude
FROM custom_qui,
     custom_sb_quoi
WHERE custom_qui.quiID = custom_sb_quoi.numqui
AND CPAct1 IS NOT NULL

UNION ALL

SELECT
  custom_qui.QuiID,
  custom_sb_quoi.numqui,
  custom_qui.CP AS CP,
  custom_qui.Latitude AS Latitude,
  custom_qui.Longitude AS Longitude
FROM custom_qui,
     custom_sb_quoi
WHERE custom_qui.quiID = custom_sb_quoi.numqui
AND CPAct1 IS NULL)
select *  from myUnion WHERE ##WHERE## ORDER BY ##ORDERBY##

P.S. if the query above works well - you can simplify it- i.e.remove your conditions (CPAct1 IS NOT NULL and CPAct1 IS NULL - they combined give you the same result set as if you don't use them) and merge everything into 1 query

This should give the same result as the query with union above:

SELECT
      custom_qui.QuiID,
      custom_sb_quoi.numqui,
      custom_sb_quoi.CPAct1 AS CP,
      custom_SB_quoi.Latitude_act AS Latitude,
      custom_SB_quoi.Longitude_act AS Longitude
    FROM custom_qui INNER JOIN custom_sb_quoi on custom_qui.quiID = custom_sb_quoi.numqui
    WHERE ##WHERE## ORDER BY ##ORDERBY##
1 votesVote for this answer Unmark Correct answer

Recent Answers


Matt Nield answered on April 28, 2018 11:15

I think your AND needs to be a WHERE. I'm not at my computer just now, but that stands out to me as not being correct SQL.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.