SQL加入两个以上的条款

时间:2015-07-01 10:36:42

标签: sql join where

我想实现以下SQL查询:假设使用JOIN子句,因为它现在运行速度很慢:

SELECT ID_USER, NICK
FROM TABLE1 
WHERE ID_USER IN 
(
    SELECT ID_INDEX1 
    FROM TABLE2 
    WHERE ID_INDEX2 = '2'
)
AND ID_USER NOT IN 
(
    SELECT ID_INDEX2 
    FROM TABLE2 
    WHERE ID_INDEX1 = '2' AND GO ='NO'
)
ORDER BY NICK ASC

2 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN执行“包含”部分,使用“LEFT JOIN”进行“排除”部分+过滤:

SELECT DISTINCT t1.ID_USER, t1.NICK
FROM TABLE1 t1
  INNER JOIN TABLE2 t2IN
    ON t1.ID_USER = t2IN.ID_INDEX1
    AND t2IN.ID_INDEX2 = '2'
  LEFT JOIN TABLE2 t2OUT
    ON t1.ID_USER = t2OUT.ID_INDEX2
    AND t2OUT.ID_INDEX1 = '2'
    AND t2OUT.GO = 'NO'
WHERE t2OUT.ID_INDEX IS NULL
ORDER BY t1.NICK ASC

答案 1 :(得分:0)

假设您希望在两种情况下按ID_INDEX1进行过滤(请参阅我对您的问题的评论),您可以:

  • 使用value = 2
  • 计算table2中每个用户的行数
  • 计算table2中每个用户的行数,其中value = 2且go ='NO'
  • 仅返回第一个计数大于0且第二个计数等于0
  • 的那些计数

即:

select * from (
  select 
    id_user,
    nick,
    sum(case when table2.id_index2 = '2' then 1 else 0 end) as count2_overall,
    sum(case when table2.id_index2 = '2' and go = 'NO' then 1 else 0 end) as count2_no
  from table1
  join table2 on table1.id_user = table2.id_index1
  group by id_user, nick
) 
where count2_overall > 0 and count2_no = 0