MySQL:将这两个子选择的结果合二为一

时间:2018-04-15 12:43:05

标签: mysql subquery

我经常搜索,但没有找到合适的答案,经过几个小时的努力,有时间问一个知道的人:)

好的,这是查询它(关闭所有不必要的内容):

SELECT 
    `id`,
    `name`,
    `details`,
    `tour_type_id`,
    `meeting_point_id`,
    `start_date`,
    `start_time`,
    `end_date`,
    `end_time`,
    `max_guests`,
    (SELECT 
            MAX(`level`)
        FROM
            `tour_notification`
        WHERE
            `model_id` = `tour`.`id`
                AND `deactivated` != 1) `notification_level`,
    (SELECT 
            MAX(`level`)
        FROM
            `guide_notification`
        WHERE
            (`tour1_id` = `tour`.`id`
                OR `tour2_id` = `tour`.`id`)
                AND `deactivated` != 1) `guide_notification_level`
FROM
    `tour`

我没有成功的是将2 MAX(level)合二为一: 从notification_levelguide_notification_level获取MAX。 我不需要单独使用这些值,我只是没有成功进入其中。

我最好的尝试是以下方法:

     (SELECT 
            MAX(`level`)
        FROM
        (SELECT `level` FROM
            `tour_notification`
        WHERE
            `model_id` = `tour`.`id`
                AND `deactivated` != 1 UNION DISTINCT SELECT `level`
        FROM
            `guide_notification`
        WHERE
            (`tour1_id` = `tour`.`id`
                OR `tour2_id` = `tour`.`id`)
                AND `deactivated` != 1) as `notifications`) `notification_level`,

但是MySQL抱怨说: 错误:错误1054:未知列' tour.id'在' where子句'

如果我将游览表添加到这些子选择的where子句中,它总是得到任何游览表项的结果,而不仅仅是当前项。

任何人都可以把我推向正确的方向吗? 非常感谢!

2 个答案:

答案 0 :(得分:0)

以下内容可能对您有用。它提供了三种不同的方法将水平组合成一列。删除你不想要的那些。

SELECT 
    a.`id`,
    a.`name`,
    a.`details`,
    a.`tour_type_id`,
    a.`meeting_point_id`,
    a.`start_date`,
    a.`start_time`,
    a.`end_date`,
    a.`end_time`,
    a.`max_guests`,
    a.`tour_level`,
    a.`guide_level`,
    CONCAT(`tour_level`," ",`guide_level`) as `notification_level1`,
    a.`tour_level` + a.`guide_level` as `notification_level2`,
    GROUP_CONCAT(CONCAT(a.`tour_level`," ",a.`guide_level`) as `notification_level3`
FROM `tour` a
LEFT JOIN `tour_notification` b
ON a.`id` = b.`model_id` AND b.`deactivated` <> 1
LEFT JOIN `guide_notification` c
ON a.`id` = c.`tour2_id` AND c.`deactivated` <> 1
GROUP BY a.`id`

答案 1 :(得分:0)

如果您需要最大值为2,则可以使用GRATEST()功能。但我认为带LIMIT 1的UNION ALL子查询更具可读性:

(
    SELECT MAX(`level`) AS `max_level`
    FROM `tour_notification`
    WHERE `model_id` = `tour`.`id`
      AND `deactivated` != 1

    UNION ALL

    SELECT MAX(`level`) AS `max_level`
    FROM `guide_notification`
    WHERE (`tour1_id` = `tour`.`id` OR `tour2_id` = `tour`.`id`)
      AND `deactivated` != 1
    ORDER BY max_level DESC
    LIMIT 1
) AS `notification_level`