SQL查询返回特定标签(如果存在)(如果不存在,则返回0)

时间:2018-12-23 16:08:14

标签: mysql sql join ifnull

给出了两个表,标签和媒体。 mysql>从媒体中选择*;

+----+---------+----------+
| id | name    | duration |
+----+---------+----------+
| 1  | cat.mp4 | 3.4      |
| 2  | dog.mp4 | 8        |
+----+---------+----------+

mysql>从标记中选择*;

+----+----------+-------+--------+------------+
| id | media_id | type  | value  | confidence |
+----+----------+-------+--------+------------+
| 1  | 1        | LABEL | cat    | 0.9        |
| 2  | 1        | LABEL | person | 0.6        |
| 3  | 1        | TEXT  | kitty  | 0.95       |
| 4  | 2        | LABEL | dog    | 0.8        |
| 5  | 2        | LABEL | person | 0.75       |
| 6  | 2        | TEXT  | food   | 0.7        |
+----+----------+-------+--------+------------+

我需要通过连接两个提供标签的值的media_id,名称,持续时间和标签的表来获得输出表,以便如果该值为cat,则cat的置信度将插入到label_cat列中,否则为0已插入。 像这样:

+----------+---------+----------+-----------+-----------+--------------+
| media_id | name    | duration | label_cat | label_dog | label_person |
+----------+---------+----------+-----------+-----------+--------------+
| 1        | cat.mp4 | 3.4      | 0.9       | 0         | 0.6          |
| 2        | dog.mp4 | 8        | 0         | 0.8       | 0.75         |
+----------+---------+----------+-----------+-----------+--------------+

2 个答案:

答案 0 :(得分:0)

如果我理解正确,则需要条件聚合:

select m.id, m.name, m.duration,
       max(case when t.value = 'cat' then t.confidence end) as label_cat,
       max(case when t.value = 'dog' then t.confidence end) as label_dog,
       max(case when t.value = 'person' then t.confidence end) as label_person
from media m left join
     tag t
     on m.id = t.media_it
group by m.id, m.name, m.duration

答案 1 :(得分:0)

    Select t.media_id,m.name,m.duration,
     case "label_cat " when t.value ='cat' then 
    t.confidence else 0 end case,
    case "label_dog" when t.value ='dog' then 
    t.confidence else 0 end case,
     case "label_person" when t.value ='person' then 
    t.confidence else 0 end case 
    from
    tag t right join media m on t.id=m.id
   group by t.media_id