使用UNION语句的SQL查询中的标记无效

时间:2018-01-04 20:33:39

标签: mysql sql

我正在尝试通过将电子邮件地址放在3个不同的表(oc_customer,oc_journal2_newsletter和oc_d_newsletter_subscriber)中来执行MySQL查询。当所有电子邮件都放入1列时,我想将其分组以避免重复并对数据进行升序排序。

我在下面有以下查询,但每次在有效执行查询之前收到有关无效令牌')'的消息。该消息指向具有代码的行.... subscribed ='1')....

有人可以帮助我避免这个警告吗?

SELECT `emailTOTAAL`.`emailTOT`
FROM (
SELECT 
  `oc_customer`.`email` AS `emailTOT`
FROM
  `oc_customer`
WHERE
  `oc_customer`.`language_id` = '2' AND 
  `oc_customer`.`newsletter` = '1'
UNION ALL
SELECT 
  `oc_journal2_newsletter`.`email` AS `emailTOT`
FROM
  `oc_journal2_newsletter`
UNION ALL
SELECT 
  `oc_d_newsletter_subscriber`.`email` AS `emailTOT`
FROM
  `oc_d_newsletter_subscriber`
WHERE
  `oc_d_newsletter_subscriber`.`language_id` = '2' AND 
  `oc_d_newsletter_subscriber`.`subscribed` = '1') 
AS `emailTOTAAL`
GROUP BY   
 `emailTOTAAL`.`emailTOT`
ORDER BY
 `emailTOTAAL`.`emailTOT` ASC

谢谢, Vicef

1 个答案:

答案 0 :(得分:1)

如果您将UNION ALL更改为UNION,则应删除重复项。然后你可以摆脱外部SELECTGROUP BY。您的查询将如下所示:

SELECT 
    `email` AS `emailTOT`
FROM
    `oc_customer`
WHERE
    `language_id` = '2' AND 
    `newsletter` = '1'

UNION

SELECT 
    `email` AS `emailTOT`
FROM
    `oc_journal2_newsletter`

UNION

SELECT 
    `email` AS `emailTOT`
FROM
    `oc_d_newsletter_subscriber`
WHERE
    `language_id` = '2' AND 
    `subscribed` = '1'
ORDER BY `emailTOT` ASC