用concat和'%'联接表不起作用

时间:2019-08-12 19:53:41

标签: sql postgresql

我有两个正在使用的表。一个是带有标题和标签的文章名称列表,另一个是日志。这两个表中唯一的共同元素是商品表中的段和日志表中的路径。所有路径均以/ article /(slug)开头。问题在于某些路径是/ article /(slug)(另一个字符)。我可以使用下面的代码加入表格。但是第二次尝试使用%却没有结果。

这有效:

SELECT log.path, articles.slug, articles.title, count(log.path) as num 
FROM articles LEFT JOIN log 
ON CONCAT('/article/', articles.slug) LIKE log.path 
GROUP BY log.path, articles.slug, articles.title 
ORDER BY num DESC;

但这不会给我带来任何令人困惑的结果,因为它应该:

SELECT log.path, articles.slug, articles.title, count(log.path) as num 
FROM articles LEFT JOIN log 
ON CONCAT('%', articles.slug) LIKE log.path 
GROUP BY log.path, articles.slug, articles.title 
ORDER BY num DESC;

我真正需要工作的是:

SELECT log.path, articles.slug, articles.title, count(log.path) as num 
FROM articles LEFT JOIN log 
ON CONCAT('%', articles.slug, '%') LIKE log.path 
GROUP BY log.path, articles.slug, articles.title 
ORDER BY num DESC;

我在做什么错了?

在这一点上,我想找到一种方法来连接两个表,该表为我提供3列:articles.slug,log.path和num。问题是我不知道如何创建一个表,该表告诉我每个路径的段,因为多个路径具有相同的段。如果我能做到这一点,则可以按表头将表分组,并使用SUM将数字加在一起,这将解决我的问题。

1 个答案:

答案 0 :(得分:0)

SQL运算符LIKE可交换的。即:x LIKE yy LIKE x不同。更具体地说,“%”和“ _”仅在右侧是通配符。

将查询更改为

    SELECT log.path, articles.slug, articles.title, count(log.path) as num 
    FROM articles LEFT JOIN log 
    ON log.path LIKE CONCAT('/article/', articles.slug)
    GROUP BY log.path, articles.slug, articles.title 
    ORDER BY num DESC;
    SELECT log.path, articles.slug, articles.title, count(log.path) as num 
    FROM articles LEFT JOIN log 
    ON log.path LIKE CONCAT('%', articles.slug)
    GROUP BY log.path, articles.slug, articles.title 
    ORDER BY num DESC;
    SELECT log.path, articles.slug, articles.title, count(log.path) as num 
    FROM articles LEFT JOIN log 
    ON log.path LIKE CONCAT('%', articles.slug, '%')
    GROUP BY log.path, articles.slug, articles.title 
    ORDER BY num DESC;

请注意,第一个查询仅适用于不涉及通配符的情况。在这种情况下,x LIKE yx = y相同(可交换的,因此在这种情况下,y LIKE x)。