简体   繁体   中英

MYSQL join two tables, with matching value from second table

i have two tables [tags] and [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'

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

ok say I want to check 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

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. If you do the comparison in the where clause, you turn the outer join into an inner join.

Also, I put in more reasonable table aliases. Don't use arbitrary letters like a for table aliases. 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. under the case operator execute the another sql query. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM