Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

mysql - Multiple UNION query doesn't work

The multiple UNION query:

SELECT [Ordine numero] AS ordine, [data ordine] AS data, comm AS commessa
FROM [archivio globale]
WHERE [ordine numero] IS NOT NULL

UNION

SELECT [numero ordine cliente] AS ordine, [data ordine cliente] AS data, numero AS commessa
FROM [ricambi]
WHERE [numero ordine cliente] IS NOT NULL

UNION

SELECT [numero ordine cliente] AS  ordine, [data ordine cliente] AS data, numero AS commessa
FROM [trasferte]
WHERE [numero ordine cliente] IS NOT NULL

ORDER BY [ordine];

It doesn't work: I get the error message:

[mysql][odbc 5.1 Driver][mysqld-5.5.14]You have an error in your SQL syntax ...

While the single UNION query works properly (without the second UNION statement)? What to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have tagged your question as MySQL and you are using square brackets []. As far as I know, square brackets are not valid for MySQL and are only valid for Microsoft products (SQL Server/MS Access). So if you need to enclose table/column name use backticks `.

From the documentation:

The identifier quote character is the backtick (“`”):

So I think your query should be:

SELECT `Ordine numero` AS ordine, `data ordine` AS data, comm AS commessa
FROM `archivio globale`
WHERE `ordine numero` IS NOT NULL

UNION ALL

SELECT `numero ordine cliente` AS ordine, `data ordine cliente` AS data, numero AS commessa
FROM `ricambi`
WHERE `numero ordine cliente` IS NOT NULL

UNION ALL

SELECT `numero ordine cliente` AS  ordine, `data ordine cliente` AS data, numero AS commessa
FROM `trasferte`
WHERE `numero ordine cliente` IS NOT NULL

ORDER BY `ordine`;

Edit, if you are using MS Access then you will need to use the square brackets:

SELECT *
FROM
(
  SELECT [Ordine numero] AS ordine, [data ordine] AS data, comm AS commessa
  FROM [archivio globale]
  WHERE [ordine numero] IS NOT NULL

  UNION ALL

  SELECT [numero ordine cliente] AS ordine, [data ordine cliente] AS data, numero AS commessa
  FROM [ricambi]
  WHERE [numero ordine cliente] IS NOT NULL

  UNION ALL

  SELECT [numero ordine cliente] AS  ordine, [data ordine cliente] AS data, numero AS commessa
  FROM [trasferte]
  WHERE [numero ordine cliente] IS NOT NULL
) x
ORDER BY [ordine];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...