使用内部n引用创建视图

时间:2013-06-11 15:51:33

标签: mysql sql

对于CMS系统,我试图在文章关系中优雅地搜索用户提供的网址。

我有两个表:一个包含文章(cms_article),另一个包含文章的特定语言内容(cms_content)。 因此cms_article中的1行可以在cms_content中有多个tupples,因为它代表文章的不同语言表示。

reference列也可以嵌套不同的文章,该列引用cms_article中的id列。如果它是顶级文章,则此cms_article.ref = NULL

表格:

cms_article  id  | ref | published  
cms_content  cid | aid | lang      | url | browserTitle | content | etc etc

从这两个表中我想创建一个可用于查找URL的视图。所以我想为cms_article中的每个给定的tupple构建一个totalURL字段,每个父/ ref作为URL的一部分。

例如,让我们回顾一下这个页面/文章的结构:

AID  English                             Dutch                               More languages
1    /Products                           /Producten
4    /Products/Product-2                 /Producten/Product-2
7    /Products/Product-2/screenshots     /Producten/Product-2/afbeeldingen
34   /Products/Product-2/pricing         /Producten/Product-2/prijzen
12   /Products/Product-5                 /Producten/Product-5
6    /About-us                           /Over-ons

每行代表cms_article关系中的文章和1个元组。网址字段来自相应的cms_content.url字段。

如何将每个元组的totalURL聚合为一个视图,以便生成如下视图:

cms_view

aid      = article ID       = integer
lang     = language         = NL|EN|... 
totalURL = agregated URL    = /products/product-2/pricing

对于上面的例子,它必须生成下表:

1  | EN | /Products
1  | NL | /Producten
4  | EN | /Products/Product-2
4  | NL | /Producten/Product-2/afbeeldingen
etc etc 

当然,我可以遍历cms_content中的每个元组,并在PHP中找到引用(并为每个级别和每个元组重复一次)。但是,由于这给服务器带来了很大的压力,我正在寻找一个像视图一样优雅的SQL解决方案。

修改

这是我走了多远,我觉得我很亲密。寻求解决方案:将urlparentURL合并到一个字段中。以及如何深入三个层次。

SELECT 
a.id AS aid, c.lang, a.ref,
c.url,
(
    SELECT c2.url
    FROM cms_content AS c2
    WHERE c2.aid = a.ref
    AND
    c2.lang = c.lang
) AS parentURL
FROM cms_content AS c
LEFT JOIN cms_article AS a ON c.aid = a.id
WHERE a.domain = 'some.url'
AND a.published =1
ORDER BY aid

1 个答案:

答案 0 :(得分:0)

如果您了解所有语言,则可以连接子查询。

示例:

SELECT
aid
, CONCATENATE( 
  CASE WHEN (SELECT langcode FROM cms_article x WHERE a.aid = x.aid AND language = 'EN')
  THEN 
    CONCATENATE(
    (SELECT langcode FROM cms_article x WHERE a.aid = x.aid AND language = 'EN')
    , '|')
  ELSE ''
  END,
  CASE WHEN (SELECT langcode FROM cms_article x WHERE a.aid = x.aid AND language = 'DU')
  THEN 
    CONCATENATE(
    (SELECT langcode FROM cms_article x WHERE a.aid = x.aid AND language = 'DU')
    , '|')
  ELSE ''
  END) as language
, CONCATENATE( 
  CASE WHEN (SELECT totalUrl FROM cms_article x WHERE a.aid = x.aid AND language = 'EN')
  THEN 
    CONCATENATE(
    (SELECT totalUrl FROM cms_article x WHERE a.aid = x.aid AND language = 'EN')
    , '|')
  ELSE ''
  END,
  CASE WHEN (SELECT totalUrl FROM cms_article x WHERE a.aid = x.aid AND language = 'DU')
  THEN 
    CONCATENATE(
    (SELECT totalUrl FROM cms_article x WHERE a.aid = x.aid AND language = 'DU')
    , '|')
  ELSE ''
  END) as agregatedUrl
FROM cms_content a