且构网

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

在 MYSQL 中有效地连接 3 个表

更新时间:2023-11-27 20:12:16

  1. SELECT i.place_id, t.name as tag_name
    来自图像 i
    INNER JOIN tagsToImages tti ON (tti.image_id = i.id)
    INNER JOIN 标签 t ON (t.id = tti.tag_id)
    哪里 i.place_id = 7

SELECT i.filename, GROUP_CONCAT(t.name SEPARATOR ',') AS 标签
来自图像 i
INNER JOIN tagsToImages tti ON (tti.image_id = i.id)
INNER JOIN 标签 t ON (t.id = tti.tag_id)
哪里 i.place_id = 4GROUP BY i.filename

如果可能,***避免多次查询.
*注意GROUP_CONCAT 的最大长度由group_concat_max_len 变量控制.如果您希望获得一长串串联字符串,则可能需要更改默认值.

It's always better to avoid multiple queries if possible.
*Be aware that the maximum length of GROUP_CONCAT is controlled by group_concat_max_len variable. If you are expecting to get a long list of concatenated strings, you might need to change the default value.

更新
如果您希望查询显示没有关联标签的图像,请将 INNER JOINs 更改为 LEFT JOINs