SQL Distinct关键字不返回多列的不同值

时间:2015-11-13 12:01:28

标签: mysql sql sql-server

如果我只选择带有Distinct的1列,那么如果我选择多个1列不同的列,它会正常工作,它会返回重复值。

SELECT
    DISTINCT MS.SRC_TABLE_NAME AS SRC_TABLE_NAME,
    MS.SRC_SYSTEM_ENVIRONMENT_NAME AS SRC_SYSTEM_ENVIRONMENT_NAME,
    MS.SRC_SYSTEM_NAME AS SRC_SYSTEM_NAME
FROM
    MAPPING_SPECIFICATION MS,
    MAPPING_DETAILS MD

WHERE
    MS.MAP_ID = MD.MAP_ID AND
    MD.STATUS = 'Active'

返回重复行

 SELECT
        DISTINCT MS.SRC_TABLE_NAME AS SRC_TABLE_NAME        
    FROM
        MAPPING_SPECIFICATION MS,
        MAPPING_DETAILS MD

    WHERE
        MS.MAP_ID = MD.MAP_ID AND
        MD.STATUS = 'Active'

如果仅选择不同的行,则完美地工作。

2 个答案:

答案 0 :(得分:1)

当您将其与其他列一起使用时,

DISTINCT并不保证您具有SRC_TABLE_NAME唯一性。你的行是DISTINCT,它的效果非常好

CREATE TABLE #MyTable(col1 INT, col2 INT);

INSERT INTO #MyTable VALUES (1,1), (1,2), (2,1),(3,1);

SELECT DISTINCT col1, col2
FROM #MyTable;

LiveDemo

使用GROUP BY代替{strong> aggregate function ,例如MIN/MAX/GROUP_CONCAT

SELECT
    MS.SRC_TABLE_NAME AS SRC_TABLE_NAME,
    MIN(MS.SRC_SYSTEM_ENVIRONMENT_NAME) AS SRC_SYSTEM_ENVIRONMENT_NAME,
    MIN(MS.SRC_SYSTEM_NAME) AS SRC_SYSTEM_NAME
FROM MAPPING_SPECIFICATION MS
JOIN MAPPING_DETAILS MD
  ON MS.MAP_ID = MD.MAP_ID AND
WHERE MD.STATUS = 'Active'
GROUP BY MS.SRC_TABLE_NAME;

还尝试避免使用逗号语法连接并使用JOIN。请注意,SQL ServerMySQL支持不同的聚合函数。

答案 1 :(得分:0)

您可以尝试使用多列来获取DISTINCT:

select 
(SELECT group_concat(DISTINCT MS.SRC_TABLE_NAME) FROM MAPPING_SPECIFICATION MS INNER JOIN MAPPING_DETAILS MD ON MS.MAP_ID = MD.MAP_ID 
WHERE MD.STATUS = 'Active') as SRC_TABLE_NAME,
(SELECT group_concat(DISTINCT MS.SRC_SYSTEM_ENVIRONMENT_NAME) FROM MAPPING_SPECIFICATION MS INNER JOIN MAPPING_DETAILS MD ON MS.MAP_ID = MD.MAP_ID 
WHERE MD.STATUS = 'Active') as SRC_SYSTEM_ENVIRONMENT_NAME,
(SELECT group_concat(DISTINCT MS.SRC_SYSTEM_NAM) FROM MAPPING_SPECIFICATION MS INNER JOIN MAPPING_DETAILS MD ON MS.MAP_ID = MD.MAP_ID 
WHERE MD.STATUS = 'Active') as SRC_SYSTEM_NAME

它在MYSQL中。

在SQL Server中,您可以像这样使用Group By:

SELECT MS.SRC_SYSTEM_NAM AS SRC_TABLE_NAME,
          MS.SRC_SYSTEM_ENVIRONMENT_NAME AS SRC_SYSTEM_ENVIRONMENT_NAME,
          MS.SRC_SYSTEM_NAME AS SRC_SYSTEM_NAME
   FROM MAPPING_SPECIFICATION MS 
        INNER JOIN MAPPING_DETAILS MD ON MS.MAP_ID = MD.MAP_ID 
   WHERE MD.STATUS = 'Active'
   GROUP BY MS.SRC_SYSTEM_NAM, MS.SRC_SYSTEM_ENVIRONMENT_NAME, MS.SRC_SYSTEM_NAME