MySQL问题与UNION连接2个表

时间:2019-11-09 10:07:50

标签: mysql sql join union

我正在MySQL中做UNION,但暂时无法进行故障排除。 错误提示

  

t1.*周围的语法不正确

这2个SELECT分别工作正常,请进行检查。但是UNION失败了。我不是自定义MySQL语法,也许这是有问题的。

SELECT (
    t1.*,
    a.region_count
  FROM
    (
      SELECT
        data_region,
        COUNT(*) AS region_count
      FROM
        t2
      GROUP BY
        data_region
    ) AS a
  LEFT OUTER JOIN
    t1
  ON
    t1.values_att0 = a.data_region
  WHERE
    t1.name_0 = 'region'
) AS b

UNION

SELECT (
  t1.*,
  c.age_gen_count
FROM
  (
    SELECT
      data_dage,
      data_gen,
      COUNT(*) AS age_gen_count
    FROM
      t2
    GROUP BY
      data_dage,
      data_gen
  ) AS c
  LEFT JOIN
    t1
  ON
    t1.values_att0 = c.data_dage AND
    t1.id_question_1 = c.data_gen
  WHERE
    t1.name_0 = 'age' AND 
    t1.q_name_1 = 'gen'
)

1 个答案:

答案 0 :(得分:3)

您在SELECT字段周围使用括号,这是语法错误的出处(不是UNION的原因)。只需删除它们:

SELECT 
  t1.*,
  a.region_count
FROM
  (
    SELECT
      data_region,
      COUNT(*) AS region_count
    FROM t2
    GROUP BY data_region
  ) AS a
LEFT OUTER JOIN t1 
  ON  t1.values_att0 = a.data_region
WHERE t1.name_0 = 'region'

UNION ALL

SELECT 
  t1.*,
  c.age_gen_count
FROM
  (
    SELECT
      data_dage,
      data_gen,
      COUNT(*) AS age_gen_count
    FROM t2
    GROUP BY data_dage, data_gen
  ) AS c
LEFT JOIN t1 
  ON  t1.values_att0 = c.data_dage 
  AND t1.id_question_1 = c.data_gen
WHERE t1.name_0 = 'age' 
  AND t1.q_name_1 = 'gen'