将两个mysql查询合并为一个

时间:2014-09-18 08:16:17

标签: mysql sql

我有一个查询将返回满足特定内连接约束的所有gis记录:

SELECT gis.id_gis, gis.titre, gis.lat, gis.lon FROM spip_gis AS `gis`
INNER JOIN spip_mots_liens AS L1 ON ( L1.id_objet = gis.id_gis AND
L1.objet='gis') WHERE (L1.id_mot = 210118) GROUP BY gis.id_gis

我有第二个查询将返回给定gis记录的articles.id_article(在此示例中为gis记录136):

SELECT articles.id_article, articles.lang, articles.titre FROM
spip_articles AS `articles` INNER JOIN spip_gis_liens AS L1 ON (
L1.id_objet = articles.id_article AND L1.objet='article') WHERE
(articles.statut = 'publie') AND (L1.id_gis = 136) GROUP BY
articles.id_article

如何扩展第一个查询,以便它还会返回每个记录各自的articles.id_article?

我在这里上传了sql架构:http://pastebin.com/8Fe0Lnx3

2 个答案:

答案 0 :(得分:2)

如果您想要单个查询,则可能很复杂。我可以做的一种方法如下:

SELECT gis.id_gis, gis.titre, gis.lat, gis.lon, articles.id_article, articles.lang, articles.titre FROM
    (
        SELECT articles.id_article AS id_article, articles.lang AS lang, articles.titre AS titre,articles.statut AS statut FROM
            spip_articles AS articles
            INNER JOIN 
            spip_gis_liens AS L1 
            ON (L1.id_objet = articles.id_article AND L1.objet='article') 
        WHERE (articles.statut = 'publie') AND (L1.id_gis = 136) 
        GROUP BY articles.id_article
    ) AS articles
    INNER JOIN
    (
        SELECT gis1.id_gis AS id_gis, gis1.titre AS titre, gis1.lat AS lat, gis1.lon AS lon FROM
            (
                SELECT gis.id_gis AS id_gis, gis.titre AS titre, gis.lat AS lat, gis.lon AS lon FROM 
                    spip_gis AS gis
                    INNER JOIN 
                    spip_mots_liens AS L1 
                    ON ( L1.id_objet = gis.id_gis AND L1.objet='gis') 
                WHERE (L1.id_mot = 210118) 
                GROUP BY gis.id_gis
            ) AS gis1
            INNER JOIN
            spip_gis_liens AS gis2
            ON ( gis1.id_gis = gis2.id_objet)
    ) AS gis
    ON (articles.id_article = gis.id_gis)

要点是递归地使用INNER JOIN基于主键互相连接,比如说'id_objet''id_article'。 每次为输出表分配新名称时,都可以更新列名称(使用AS)。

答案 1 :(得分:1)

你可以尝试这个查询并告诉我它返回什么

SELECT gsis.id_gis, gsis.titre, gsis.lat, gsis.lon, articlesGen.id_article, articlesGen.lang, 
articlesGen.titre
from 
(SELECT gis.id_gis, gis.titre, gis.lat, gis.lon FROM spip_gis AS `gis`
INNER JOIN spip_mots_liens AS L1 ON ( L1.id_objet = gis.id_gis AND
L1.objet='gis') WHERE (L1.id_mot = 210118) GROUP BY gis.id_gis) gsis
inner join 
(SELECT articles.id_article, articles.lang, articles.titre,L1.id_gis FROM
spip_articles AS `articles` INNER JOIN spip_gis_liens AS L1 ON (
L1.id_objet = articles.id_article AND L1.objet='article') WHERE
(articles.statut = 'publie') AND (L1.id_gis = 136) GROUP BY
articles.id_article ) articlesGen
on articlesGen.id_gis = gsis.id_gis