如果我只选择带有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'
如果仅选择不同的行,则完美地工作。
答案 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 Server
和MySQL
支持不同的聚合函数。
答案 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