代码之家  ›  专栏  ›  技术社区  ›  Rabbott

MySQL基于其他列使用特定列

  •  0
  • Rabbott  · 技术社区  · 16 年前

    我有个问题:

    SELECT COUNT(articles.id) AS count 
    FROM articles, xml_documents, streams 
    WHERE articles.xml_document_id = xml_documents.id 
    AND xml_documents.stream_id = streams.id
    AND articles.published_at BETWEEN '2010-01-01' AND '2010-04-01'
    AND streams.brand_id = 7
    

    它只使用默认的equaljoin,在FROM子句中指定三个csv格式的表。。我需要做的是根据articles.source(原始xml)中的值对其进行分组。。所以可能会变成这样:

    SELECT COUNT(articles.id) AS count, ExtractValue(articles.source, "/article/media_type") AS media_type
    FROM articles, xml_documents, streams 
    WHERE articles.xml_document_id = xml_documents.id 
    AND xml_documents.stream_id = streams.id
    AND articles.published_at BETWEEN '2010-01-01' AND '2010-04-01'
    AND streams.brand_id = 7
    GROUP BY media_type
    

    文章来源 提取值 方法将有两种不同的格式。。所以我需要做的是,如果xml\u documents.type='source one',使用“/article/media\u type”,如果xml\u documents.type='source two',使用“/article/source”

    如果能用三元运算符就好了,但我认为这是不可能的。。

    编辑 在这一点上,我正在考虑制作一个临时表,或者简单地使用UNION将多个结果集放在一起。。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Jason Day    16 年前

    像这样的事情怎么样:

    SELECT COUNT(articles.id) AS count,
           ExtractValue(articles.source,
               CASE xml_documents.type WHEN 'source one' then '/article/media_type'
                                       WHEN 'source two' then '/article/source'
                                       ELSE 'error'
               END),
    FROM ...
    

    编辑 试试这个:

    SELECT COUNT(articles.id) AS count,
           CASE xml_documents.type WHEN 'source one' THEN ExtractValue(articles.source, '/article/media_type')
                                   WHEN 'source two' THEN ExtractValue(articles.source, '/article/source')
                                   ELSE NULL
           END as media_type,
    ...
    
        2
  •  0
  •   newtover    16 年前

    SELECT
        COUNT(articles.id) AS count,
        (CASE xml_documents.type
            WHEN 'source one' THEN ExtractValue(articles.source, '/article/media_type')
            WHEN 'source two' then ExtractValue(articles.source, '/article/source')
            ELSE NULL
        END) as media_type,
    FROM ...
    
    推荐文章