加入时从orignial表中删除双重条目

时间:2016-04-22 14:09:48

标签: mysql sql join

我有两张桌子: 我发送的地址和文件日志(名为send)。

对于给定的文件,我想获取所有地址,以及是否收到了该文件。

到目前为止我得到的是:

SELECT            *
,                 CASE 
                      WHEN send.fileid = 1 THEN 1 
                      ELSE send.fileid = NULL 
                  END as file1 
FROM              send
RIGHT OUTER JOIN `adress` 
              ON `send`.adressid = `adress`.`id`

问题是,当一个地址有两个不同的文件时,它们会被列出两次。我怎样才能改变声明来解决这个问题?

示例数据

*adress*
1 Adrian
2 Christian
3 Max
4 Alex

*file*
1 music
2 video
3 document

*send*
adress:1 file:1
adress:1 file:2 -
adress:3 file:1
adress:4 file:2 -
adress:4 file:3

when i browse the file 2, i want to see:
X Adrian
X Alex
Christian
Max

TLDR:我希望我的所有地址(一次)具有特定的文件ID或null。

提前致谢。

3 个答案:

答案 0 :(得分:0)

一种方法是将条件置于子查询中,让外连接完成所有繁重的工作:

SELECT    a.*, s.fieldid
FROM      address a
LEFT JOIN (SELECT filedid, addressid
           FROM   send
           WHERE  fileid = 1) ON s.addressid = a.id

答案 1 :(得分:0)

当然,您只需使用GROUP BY即可完成此操作吗?

我把一个快速的例子放在一起,然后意识到这是MySQL。我认为基本方法是相同的,但该示例不起作用。因为这是SQL Server语法:

DECLARE @address TABLE (address_id INT, address_name VARCHAR(50));
INSERT INTO @address SELECT 1, 'Adrian';
INSERT INTO @address SELECT 2, 'Christian';
INSERT INTO @address SELECT 3, 'Max';
INSERT INTO @address SELECT 4, 'Alex';
DECLARE @file TABLE ([file_id] INT, [file_name] VARCHAR(50));
INSERT INTO @file SELECT 1, 'music';
INSERT INTO @file SELECT 2, 'video';
INSERT INTO @file SELECT 3, 'document';
DECLARE @send TABLE (address_id INT, [file_id] INT);
INSERT INTO @send SELECT 1, 1;
INSERT INTO @send SELECT 1, 2;
INSERT INTO @send SELECT 3, 1;
INSERT INTO @send SELECT 4, 2;
INSERT INTO @send SELECT 4, 3;

SELECT
    a.address_id,
    a.address_name,
    MAX(CASE WHEN f.[File_id] = 1 THEN 'X' END) AS file_1,
    MAX(CASE WHEN f.[File_id] = 2 THEN 'X' END) AS file_2,
    MAX(CASE WHEN f.[File_id] = 3 THEN 'X' END) AS file_3
FROM
    @address a
    LEFT JOIN @send s ON s.address_id = a.address_id
    LEFt JOIN @file f ON f.[file_id] = s.[file_id]
GROUP BY
    a.address_id,
    a.address_name
ORDER BY
    a.address_id;

这给出了一个地址和文件矩阵,即:

address_id  address_name    file_1  file_2  file_3
1           Adrian          X       X       NULL
2           Christian       NULL    NULL    NULL
3           Max             X       NULL    NULL
4           Alex            NULL    X       X

答案 2 :(得分:0)

SELECT * 
FROM adress
LEFT JOIN send ON send.adressid = adress.id
AND send.fileid =1
LIMIT 0 , 30

似乎是它