连接多个表时删除行重复-MySQL

时间:2019-03-13 14:02:48

标签: mysql database

媒体

id  | title   | ...
1   | a song  |
2   | a video |

媒体设置

media_id  | setting_id  | chosen_option
  1       |    1        |    2
  1       |    2        |    3
  2       |    1        |    1
  2       |    2        |    4

因此,我有一个媒体表,其中包含有关用户上传的媒体文件的各种信息,并且它们具有两个设置1.privacy( option-1 for public and option-2 for private)2.age-safty( option-3 is for all and option-4 is for adult only)。现在,当用户(成人)搜索媒体时,假设标题以a....开头。

这是我的查询:

SELECT 
m.id AS media_id, m.title AS media_title, 
ms.setting_id AS setting, ms.chosen_option as opt 
FROM media m 
LEFT JOIN media_setting ms ON m.id = ms.media_id
WHERE m.title LIKE 'a%'

AND它将为我提供重复行的输出,每一行不需要我想要的每个设置。

所以我想要的是:

media_id  |  media_title  | setting_1  | option_for_1 |  setting_2 | option_for_2

1         |  a song       |   1        |    2         |    2        |     3
2         |  a video      |   1        |    1         |    2        |     4

我该如何实现?谢谢。

1 个答案:

答案 0 :(得分:1)

根据评论,我会坚持使用您所拥有的查询,并解决应用程序代码中的显示问题。

但是无论如何,这是sql中的一种标准(非动态)方法...

CREATE TABLE media
(id SERIAL PRIMARY KEY
,title VARCHAR(20) NOT NULL
);

INSERT INTO media VALUES
(1,'a song'),
(2,'a video');

DROP TABLE IF EXISTS media_setting;

CREATE TABLE media_setting
(media_id INT NOT NULL
,setting_id INT NOT NULL
,chosen_option INT NOT NULL
,PRIMARY KEY(media_id,setting_id)
);

INSERT INTO media_setting VALUES
(1,1,2),
(1,2,3),
(2,1,1),
(2,2,4);

SELECT m.*
     , MAX(CASE WHEN s.setting_id = 1 THEN chosen_option END) option_for_1
     , MAX(CASE WHEN s.setting_id = 2 THEN chosen_option END) option_for_2
  FROM media m
  LEFT
  JOIN media_setting s 
    ON s.media_id = m.id
 GROUP
    BY m.id;

+----+---------+--------------+--------------+
| id | title   | option_for_1 | option_for_2 |
+----+---------+--------------+--------------+
|  1 | a song  |            2 |            3 |
|  2 | a video |            1 |            4 |
+----+---------+--------------+--------------+