如何获取两个 sql 查询并将它们组合成一个查询

Posted

技术标签:

【中文标题】如何获取两个 sql 查询并将它们组合成一个查询【英文标题】:How to take two sql queries and combine them into a single query 【发布时间】:2018-11-07 20:56:10 【问题描述】:

我正在为我的程序编写自定义脚本:

// You might want to use a date range and specify the first Sunday and use that variable.
// Or, you may want to have a user request variable where they key in the starting Sunday #YYYY MM DD#

// Let us work out the current week number
$iStartWeekNumber = $Today#CUSTOMDATE[%W] + 1
TEXT "Current week number (1 to 52): $iStartWeekNumber"
EOL

// Let us work out the current year
$iThisYear = $Today#CUSTOMDATE[%Y]
TEXT "Current year: $iThisYear"
EOL

// Now we can do a manual for loop from iStartWeekNumber to the end of the year
TEXT "TODO: Work out how to show the date nicely formatted"
EOL
$datWeek = $Today
LOOP AS $iWeekNumber FROM $iStartWeekNumber TO 52
    $datWeek = $datWeek + 7
    TEXT "Week: $iWeekNumber"
    EOL
    TEXT "Date: $datWeek#SHORTDATE"
    EOL

    // Iterate all available speakers
    LOOP FROM "Congregation Speakers" NODATERANGE WHERE "Congregation" IS "$LocalCong" AND "notavail" IS "0"  SORTBY "Speaker"

        // Requirement 1
        // 1. He is not in program for a talk in our home or another congregation for that same WEEKEND (either saturday or sunday)

        // Store the current speaker into a variable
        VARIABLE_FIELD "Speaker" "$strCurrentSpeaker"

        LOOP SQL "SELECT * FROM [Home Talks] WHERE ((DatePart('ww',[Last Given],2)=$iWeekNumber)) AND ((DatePart('yyyy',[Last Given])=$iThisYear)) AND [Speaker] = '$strCurrentSpeaker' AND [Congregation]='$LocalCong'" ROW_COUNT "$iNumHomeTalks"
        END_LOOP

        LOOP SQL "SELECT * FROM [Away Talks] WHERE ((DatePart('ww',[Talk Date],2)=$iWeekNumber)) AND ((DatePart('yyyy',[Talk Date])=$iThisYear)) AND [Brother] = '$strCurrentSpeaker'" ROW_COUNT "$iNumAwayTalks"
        END_LOOP

        IF "$iNumHomeTalks" IS "0" AND "$iNumAwayTalks" IS "0"
            // Requirement 2
            // 2. He should not give a talk more than once in a MONTH (so he is unavailable if he will be giving a talk during the month)
            $iMonth = date_part($datWeek,"M")
            LOOP SQL "SELECT * FROM [Home Talks] WHERE ((DatePart('m',[Last Given])=$iMonth)) AND ((DatePart('yyyy',[Last Given])=$iThisYear)) AND [Speaker] = '$strCurrentSpeaker' AND [Congregation]='$LocalCong'" ROW_COUNT "$iNumHomeTalksForMonth"
            END_LOOP
            LOOP SQL "SELECT * FROM [Away Talks] WHERE ((DatePart('m',[Talk Date])=$iMonth)) AND ((DatePart('yyyy',[Talk Date])=$iThisYear)) AND [Brother] = '$strCurrentSpeaker'" ROW_COUNT "$iNumAwayTalksForMonth"
            END_LOOP
            $iTotalTalksForMonth = $iNumHomeTalksForMonth + $iNumAwayTalksForMonth
            IF "$iTotalTalksForMonth" IS "0"
                // Requirement 3
                // 3. That same weekend either one or more than x speakers are not out for a talk or unavailable

                // TO DO
                TEXT "$strCurrentSpeaker"
                EOL
            END_IF
        END_IF
    END_LOOP

    BLANK *1
END_LOOP

我想特别提请您注意两组 SQL 查询

第一组:

LOOP SQL "SELECT * FROM [Home Talks] WHERE ((DatePart('ww',[Last Given],2)=$iWeekNumber)) AND ((DatePart('yyyy',[Last Given])=$iThisYear)) AND [Speaker] = '$strCurrentSpeaker' AND [Congregation]='$LocalCong'" ROW_COUNT "$iNumHomeTalks"
END_LOOP
LOOP SQL "SELECT * FROM [Away Talks] WHERE ((DatePart('ww',[Talk Date],2)=$iWeekNumber)) AND ((DatePart('yyyy',[Talk Date])=$iThisYear)) AND [Brother] = '$strCurrentSpeaker'" ROW_COUNT "$iNumAwayTalks"
END_LOOP

并设置 2:

LOOP SQL "SELECT * FROM [Home Talks] WHERE ((DatePart('m',[Last Given])=$iMonth)) AND ((DatePart('yyyy',[Last Given])=$iThisYear)) AND [Speaker] = '$strCurrentSpeaker' AND [Congregation]='$LocalCong'" ROW_COUNT "$iNumHomeTalksForMonth"
END_LOOP
LOOP SQL "SELECT * FROM [Away Talks] WHERE ((DatePart('m',[Talk Date])=$iMonth)) AND ((DatePart('yyyy',[Talk Date])=$iThisYear)) AND [Brother] = '$strCurrentSpeaker'" ROW_COUNT "$iNumAwayTalksForMonth"
END_LOOP

以上是我自己的脚本语言。但在底层,它采用原始 SQL 查询并使用 Jet 在 Microsoft Access 数据库上运行它。

他们工作得很好。但是我想知道这两组查询是否可以合并为一组?如您所见,我试图建立的只是找到的记录数。因此,如果我可以结合 [Home Talks][Away Talks] 的查询,我最终将只执行 2 个查询而不是 4 个。

在我看来,我需要使用UNION,但每个表中的一个字段不同:

Last Given Talk Date

所以我不能只在两个查询之间拼接关键字UNION

【问题讨论】:

【参考方案1】:

您可以通过别名字段名称来使用UNION

SELECT [Last Given] AS MyFieldName FROM [Home Talks]
UNION
SELECT [Talk Date] AS MyFieldName FROM [Away Talks]

您只需列出单个字段而不是 *,并确保任何输出字段匹配类型(或转换为字符串作为查询的一部分)和名称(别名)。

编辑:如果两个字段完全不相关(与具有不同字段名称的相同或相似信息相反),这是一个附加选项:

SELECT [Last Given], NULL AS [Talk Date] FROM [Home Talks]
UNION
SELECT NULL AS [Last Given], [Talk Date] FROM [Away Talks]

【讨论】:

那么对于两个SELECT 语句的条件,它们是使用别名字段名称还是原始名称? WHEREHAVING 部分中的原始名称,只要您不使用表别名或子查询。 我又添加了一个选项,用于两个表中的字段在上下文中不匹配而不仅仅是在名称中匹配的情况。同样的原则也可用于一个或多个UNIONed 表/查询中完全缺失的字段。

以上是关于如何获取两个 sql 查询并将它们组合成一个查询的主要内容,如果未能解决你的问题,请参考以下文章

如何组合两个查询并将数据放入一行?

如何将这两个 SQL 查询组合成一个查询?

如何将 4 个 sql 查询组合成一个性能良好的查询?

如何将这两个查询组合成一个查询?

将多个查询组合成一个查询

如何获取多个Sample()矢量输出并将它们组合成一个数据帧