简体   繁体   中英

How to distinct result in SQL VIEW select query with JOIN?

I have a view with select query with join.

SELECT
 t.a, 
 t.b,
 (SELECT CASE WHEN t2.field IS NULL THEN 0 ELSE 1 END AS Expr1) AS C
FROM table1 t1
LEFT JOIN table2 t2 on t2.link = t1.link

If in table2 there is more than 1 entry with same link, i'm getting duplicated entries.

What is the correct way to distinct result? Is there a type of JOIN, that won't return all result, but only single row?

Thank you

select distinct t.a, t.b ...

应该消除重复。

If they are really duplicates, if you use distinct they are removed:

SELECT
 distinct
 t.a, 
 t.b,
 (SELECT CASE WHEN t2.field IS NULL THEN 0 ELSE 1 END AS Expr1) AS C
FROM table1 t1
LEFT JOIN table2 t2 on t2.link = t1.link
SELECT
    t.a, 
    t.b,
    CASE WHEN EXISTS (SELECT * FROM table2 t2 WHERE t2.link = t1.link) 
           THEN 1 
           ELSE 0
    END AS c
FROM table1 t1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM