gpt4 book ai didi

一次查询中的 MySQL 3 个表?

转载 作者:行者123 更新时间:2023-11-29 07:14:46 24 4
gpt4 key购买 nike

我正在尝试创建一个高效的查询,该查询将从数据库中检索“项目”以及已分配给该特定项目的所有相关“标签”。

我的表设置模仿了 wordpress 的设置,有点复杂:

term
- Where I define the tags name, slug etc

term_relationships
- Links the project to a term in the above table.

term_taxonomy
- Defines the taxonomy of each of terms in the term table e.g. 'category', 'tag'.

因此,我需要做的是首先在 term_taxonomy 表中查询带有分类“标签”的任何条目,然后过滤这些结果,以便仅返回 term_relationships 中指定的术语。最后我需要查询术语表以返回相关标签。

我的问题是哪种方法最快?我想最好将它分成多个查询,例如。查询 1:检索项目,查询 2:检索项目标签,但请考虑我可能每页最多有 20-30 个项目。

PS:我知道只创建一个专门用于标记的新表会容易得多,但我现在想将其限制在我当前的设置中。

任何帮助将不胜感激,因为这让我发疯!

最佳答案

select     p.id
, p.name
, group_concat(t.text order by t.text) as tags
from project p
left join term_relationships tr
on p.id = tr.project_id
left join term t
on tr.term_id = t.id
left join term_taxonomy tt
on t.term_taxonomy_id = tt.id
and 'tag' = tt.type
group by p.id

请注意 group by子句不包括项目中所有选定的列 - 其他数据库会提示这个,但 Msql 不会。另请注意,在这种情况下这样做是完全有效的,因为 p.id是项目的主键,所以只能有一个不同的namep.id 的值(value).

请注意 RE GROUP_CONCAT() :

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:

SET [GLOBAL | SESSION] group_concat_max_len = val;

参见 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

因此,提前决定标签列表的大小,并将@@group_concat_max_len 设置为该值。

关于一次查询中的 MySQL 3 个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2072880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com