MySQL UNION来自一个具有不同参数的表

时间:2015-06-01 07:46:51

标签: mysql

表包含有关停车区的信息。每个区域最多可以有三行 - 一个用于工作日,一个用于星期日,一个用于星期六。列{% assign my_locations = "{{ travel_locations | split:',' | jsonify }} %} is_workday is_saturday表示一周中的几天。所有字段都可以设置为is_sunday - 它表示整周的参数相同。

我正在尝试获取所有区域信息,并在一个查询中为一周中的不同日期设置不同的别名。

1

此查询的结果是错误: SELECT t.zone_id, t.saturday_start_time, t.workday_start_time, t.sunday_start_time FROM ( (SELECT `zone_id`, `start_time` as `saturday_start_time` FROM `p2_zone_rates` WHERE `is_saturday`='1' ORDER BY `zone_id`) UNION ALL (SELECT `zone_id`, `start_time` as `workday_start_time` FROM `p2_zone_rates` WHERE `is_workday`='1' ORDER BY `zone_id`) UNION ALL (SELECT `zone_id`, `start_time` as `sunday_start_time` FROM `p2_zone_rates` WHERE `is_sunday`='1' ORDER BY `zone_id`) ) AS t GROUP BY `zone_id`

只有来自所有人的第一个查询创建别名,但其他查询使用它而不是创建新别名。

导致此错误的原因是什么?如何解决?

2 个答案:

答案 0 :(得分:0)

你必须在每个联盟中添加2列

    SELECT t.zone_id, t.saturday_start_time, t.workday_start_time, t.sunday_start_time
    FROM
    (
    (SELECT `zone_id`, `start_time` as `saturday_start_time` ,
    '' as workday_start_time, '' as sunday_start_time FROM `p2_zone_rates` WHERE `is_saturday`='1' ORDER BY `zone_id`)
    UNION ALL
    (SELECT `zone_id`, `start_time` as `workday_start_time`,
    '' as workday_start_time, '' as sunday_start_time  FROM `p2_zone_rates` WHERE `is_workday`='1' ORDER BY `zone_id`)
    UNION ALL
    (SELECT `zone_id`, `start_time` as `sunday_start_time`,
'' as workday_start_time, '' as sunday_start_time  FROM `p2_zone_rates` WHERE `is_sunday`='1' ORDER BY `zone_id`)
    ) AS t
    GROUP BY `zone_id`

答案 1 :(得分:0)

您可以像这样进行查询

SELECT t.zone_id, (CASE WHEN `is_saturday`='1' THEN start_time ELSE NULL END) as `saturday_start_time` ,
(CASE WHEN `is_workday`='1' THEN start_time ELSE NULL END) as `workday_start_time`,
(CASE WHEN `is_sunday`='1' THEN start_time ELSE NULL END) as `sunday_start_time`;

您可以根据要求添加订单或按组添加