且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取特定类别的所有帖子

更新时间:2023-08-26 21:06:28

我怀疑您的CONCAT函数可能存在问题,因为它混合了不同类型的引号.我认为"[""]"应该分别是'['']'.

I suspect there might be issues with your CONCAT function, as it mixes different types of quotation marks. I think "[" and "]" should be respectively '[' and ']'.

否则,问题似乎出在联接之一上.特别是INNER JOIN Kategorie没有指定连接条件,我认为应该是Post_Kategorie.Kategorie_ID = Kategorie.ID.

Otherwise, the problem does seem to be with one of the joins. In particular, INNER JOIN Kategorie does not specify the joining condition, which, I think, should be Post_Kategorie.Kategorie_ID = Kategorie.ID.

因此整个查询应该是这样的:

There entire query should thus be something like this:

SELECT Post.headline, Post.date, Post.ID,
  CONCAT(
    "[", GROUP_CONCAT('{"name":"',Kategorie.name,'","id":',Kategorie.ID,'}'), "]"
  ) as "categorys"
FROM Post
INNER JOIN Post_Kategorie
  ON Post.ID = Post_Kategorie.post_ID
INNER JOIN Kategorie
  ON Post_Kategorie.Kategorie_ID = Kategorie.ID
WHERE Post.public = 1
  AND Post.type = 0
GROUP BY Post.headline, Post.date
HAVING MAX(CASE Post_Kategorie.kategorie_ID WHEN 2 THEN 1 ELSE 0 END) = 1
ORDER BY Post.date DESC
LIMIT 0, 20

Post_Kategorie.kategorie_ID = 2条件已被修改为CASE表达式,并移至了HAVING子句,它与MAX()聚合函数一起使用.其工作原理如下:

The Post_Kategorie.kategorie_ID = 2 condition has been modified to a CASE expression and moved to the HAVING clause, and it is used together with the MAX() aggregate function. This works as follows:

  • 如果一个帖子被一个或多个属于Kategorie.ID = 2的标签标记,则CASE表达式将返回1,MAX的求值也将为1.因此,所有组都将有效并保留在输出中.

  • If a post is tagged with a tag or tags belonging to Kategorie.ID = 2, the CASE expression will return 1, and MAX will evaluate to 1 too. Consequently, all the group will be valid and remain in the output.

如果没有标记过帖子的标签属于上述类别,则CASE表达式将永远不会等于1,MAX也不会.结果,整个组将被丢弃.

If no tag the post is tagged with belongs to the said category, the CASE expression will never evaluate to 1, nor will MAX. As a result, the entire group will be discarded.