[英]MYSQL join two tables, with matching value from second table
i have two tables [tags] and [tags_to_item] 我有两个表[tags]和[tags_to_item]
tag_id name tag_id item_id
------ ------- ------ -------
1 Pirate 1 3
2 Monkey 2 9
3 Ninja 3 12
4 Spaghetti 4 3
the first one is a table of tags, the second stores the relations between tag and item 第一个是标签表,第二个标签和项目之间的关系
eg. 例如。
item 12 is associated with tag 'Ninja' item 3 is associated with tag 'Pirate' and 'Spaghetti' 项目12与标签“ Ninja”相关联。项目3与标签“ Pirate”和“ Spaghetti”相关联
given these tables i want to join them so I can show all the tags available, BUT showing which of those tags have been associated with a given item id 给定这些表,我想加入它们,以便显示所有可用标签,但显示哪些标签与给定项目ID相关联
ok say I want to check item_id = 3 好吧,我想检查item_id = 3
Desired output: 所需的输出:
tag_id name item_id
------ ------- -------
1 Pirate 3
2 Monkey null
3 Ninja null
4 Spaghetti 3
i tried this query but it doesn't work as expected...it doesn't show the full list 我尝试了此查询,但未按预期方式工作...未显示完整列表
SELECT a.name, a.tags_id, o.item_id from tags as a
left outer join tags_to_item as o on a.tags_id = o.tags_id WHERE o.item_id = 3
union all
select a.name, a.tags_id, o.item_id from tags as a
right outer join tags_to_item as o on a.tags_id = o.tags_id
UPDATE : 更新 :
thank to @Gordon I' getting closer to what I need, this is a decent query 感谢@Gordon我离我越来越近了,这是一个不错的查询
SELECT a.tags_name, a.tags_id, o.item_id from tags as a
left join tags_to_item as o on a.tags_id = o.tags_id AND o.item_id = 3
union
select a.tags_name, a.tags_id, o.item_id from tags as a
right join tags_to_item as o on a.tags_id = o.tags_id AND o.item_id = 3 where a.tags_id != null
I think this is what you want: 我认为这是您想要的:
select t.tags_name, t.tags_id, tti.item_id
from tags t left join
tags_to_item tti
on a.tags_id = o.tags_id and tti.item_id = 3;
Note that the condition on the item has been moved from the where
clause to the on
clause. 请注意,该项目的条件已从where
子句移至on
子句。 If you do the comparison in the where
clause, you turn the outer join into an inner join. 如果在where
子句中进行比较,则将外部联接转换为内部联接。
Also, I put in more reasonable table aliases. 另外,我输入了更合理的表别名。 Don't use arbitrary letters like a
for table aliases. 请勿使用诸如表别名之类a
任意字母。 Use table abbreviations. 使用表的缩写。
Used below query this is working. 在下面的查询中使用,此方法有效。
select t.tag_id,t.name ,
(case when (select tag_id from tags where tag_id=tti.item_id)
THEN
tti.item_id
ELSE
NULL
END) as item_id
from tags as t
left join tag_to_item as tti ON tti.tag_id = t.tag_id;
Used mysql case operator. 用过的mysql case运算符。 under the case operator execute the another sql query. 在case运算符下执行另一个sql查询。 where checked tags table having current item_id or not.if tags table having item_id then show the item_id other wise show the null string. 其中选中的标签表是否具有当前item_id。如果标签表具有item_id,则显示item_id,否则显示空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.