MySql UNION SELECT缺少字段

时间:2016-02-12 15:53:11

标签: mysql union mysql-error-1222

我越来越沮丧,因为我不明白为什么在我的UNION中我错过了一些字段。 我阅读了关于这个的好文档,并且我遵循最常见的例子,避免在第一个和第二个SELECT之间获得不同数量的列。

它包括添加NULL列,在两个语句之间达到偶数列。

我的情况:

$query = "(SELECT GC.GroupNO AS GroupNO,
    GC.Name AS Name,
    GC.Pax AS Pax,
    GC.Start AS Start,
    NULL AS custid,
    NULL AS firstname,
    NULL AS lastname,
    NULL AS arrivaldate,
    NULL AS hour,
    NULL AS pax,
    NULL AS cctype,
    NULL AS created,
    NULL AS sid,
    NULL AS ref_source,
    NULL AS numnights
  FROM LargeGroupHostels, GroupContacts AS GC
   WHERE LargeGroupHostels.HostelNumber = %d
   AND LargeGroupHostels.Status = %s
   AND LargeGroupHostels.GroupNO = GC.GroupNO";
   AND GC.Start < %s
   ORDER BY LastUpdated DESC LIMIT %d, %d
   )UNION(
    SELECT
    NULL AS GroupNO,
    NULL AS Name,
    NULL AS Pax,
    NULL AS Start,
    `custid`,
    `firstname`,
    `lastname`,
    `arrivaldate`,
    `hour`,
    `pax`,
    `cctype`,
    `created`,
    `sid`,
    `ref_source`,
    datediff(departdate, arrivaldate) AS numnights
    FROM customer_details
    WHERE hostelnumber = %d
    AND lastupdated = "" AND status != "CANX"
    AND booking_type IN ("HOSTEL", "HOSTELPACK")
    ORDER BY customer_details.arrivaldate, customer_details.created
    LIMIT %d, %d )
    ';

除了一些优化和一些我知道要做的改变之外,我的问题是:   - 为什么我没有列GC.Name,GC.Pax,GC.Start?如果我反转两个SELECT,那么只考虑GC.Name,GC.Pax,GC.Start并避开其他列,它恰好相反。

我不是那么练习这种查询,这是我第一次处理这个问题。我确定我错过了什么,但我不明白是什么

2 个答案:

答案 0 :(得分:1)

您正在尝试UNION,例如GC.name Name。这些被MySQL解释为两个独立的列,因为它无法智能地猜测你的意图(并且可能不具备这种能力)。您应该在第一个SELECT语句中为当前没有别名的列名添加别名:

SELECT GC.GroupNO AS GroupNO,
GC.Name AS Name,
GC.Pax AS Pax,
GC.Start AS Start,

在所有其他情况下,您的别名或原始列名称匹配。

我也同意上面的一条评论,这可能更适合某种类型的JOIN。

答案 1 :(得分:0)

似乎列的位置不一样

$query = "(SELECT GC.GroupNO,
GC.Name,
 .....
NULL AS ref_source
FROM LargeGroupHostels, GroupContacts AS GC

SELECT
   NULL AS Name,

  ....

  datediff(departdate, arrivaldate) as numnights
  FROM customer_details

在第一栏中的第一栏中你有第二栏中没有的栏目,而在第二栏你有第二栏的栏目没有matc和第二栏选择