如何从连接查询中获取一列的DISTINCT值

时间:2014-09-25 19:30:57

标签: mysql sql inner-join distinct

我有一个像

这样的查询
SELECT DISTINCT table_1.id_1,
    table_1.id_2,
    table_1_id_3
FROM table_1
INNER JOIN table_2
    ON table_1.id_1 = table_2.id_1
        AND table_1.id_2 = table_2.id_2
INNER JOIN table_3
    ON table_2.id_1 = table_3.id_2
        AND table_2.id_2 = table_3.id_2
WHERE table_2.code = 'Y'
    AND table_2.site = 'N'
    AND table_3.code = 'Q'

这为我提供了满足条件的id_1,id_2和id_3的独特组合。查询应该如何获得仅匹配所有条件的id_1的不同值。

我没有发布表格内容,因为它们有大量的列,而且这个问题是特定于查询的。

1 个答案:

答案 0 :(得分:1)

您可以从查询中删除第二个和第三个字段。

SELECT DISTINCT 
    table_1.id_1    
FROM table_1
INNER JOIN table_2
    ON table_1.id_1 = table_2.id_1
        AND table_1.id_2 = table_2.id_2
INNER JOIN table_3
    ON table_2.id_1 = table_3.id_2
        AND table_2.id_2 = table_3.id_2
WHERE table_2.code = 'Y'
    AND table_2.site = 'N'
    AND table_3.code = 'Q'