【问题标题】:SQL query to return specific labels if exist (0 if it does not exist)如果存在则返回特定标签的 SQL 查询(如果不存在则返回 0)
【发布时间】:2019-05-23 03:01:29
【问题描述】:

给出了两个表,标签和媒体。 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         |
+----------+---------+----------+-----------+-----------+--------------+

【问题讨论】:

  • 欢迎来到 SO Pankti。请说明您到目前为止尝试了什么。
  • 如果可以的话,请发布您到目前为止所尝试的内容
  • @PanktiPatel 详细了解如何解决 MySQL 数据透视表 are found here。希望对您有所帮助。

标签: mysql sql join ifnull


【解决方案1】:
    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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2020-04-17
      • 1970-01-01
      相关资源
      最近更新 更多