SQL查询内部连接在一定条件下

时间:2017-04-26 01:29:34

标签: mysql sql

我有这个用于创建视图的Sql查询。但是我需要重构它,因此它只会在 SALES.PKY 具有重复值或不唯一时才执行内连接。我怎么能在一个查询中做到这一点?

SELECT *
FROM SALES
INNER JOIN MAIN ON 
REPLACE(MAIN.KEY,'-','') = SALES.PKY 
AND REPLACE (MAIN.B,' ','') = SALES.SK
AND REPLACE (MAIN.P,' ','') = SALES.SP

2 个答案:

答案 0 :(得分:0)

你可以使用with语句来过滤这样吗?

with dups as (
select *
from sales
group by dup_value
having dup_value>1
)
select
dups.*
,main.*
from dups
inner join main
on dups_key=main_key

答案 1 :(得分:0)

这是一种方法:

SELECT *
FROM SALES INNER JOIN
     MAIN 
     ON REPLACE(MAIN.KEY,'-','') = SALES.PKY AND
        REPLACE(MAIN.B,' ','') = SALES.SK AND
        REPLACE(MAIN.P,' ','') = SALES.SP JOIN
     (SELECT s.PKY
      FROM SALES s
      GROUP BY s.PKY
      HAVING COUNT(*) > 1
     ) ss
     ON ss.PKY = SALES.PKY;