将NOT EXISTS查询和普通SELECT查询组合到一个语句中

时间:2016-11-08 13:38:30

标签: mysql not-exists

我在多个表中有一个查询:

SELECT s.id, st.service_type, s.service_measure, sp.id as `service_prov_id`,
sp.service_prov_name
from service s, service_prov_type_assign spta, service_prov_type_service_assign sptsa, 
service_type st, service_type_assign sta, service_provider sp 
WHERE sp.id = '3' AND spta.service_prov_id = sp.id AND
sptsa.service_prov_type_id = spta.service_prov_type_id AND 
s.id = sptsa.service_id AND sta.service_id = s.id AND 
st.id = sta.service_type_id

查询结果如下:

id | service_type | service_measure | service_prov_id | service_prov_name
--------------------------------------------------------------------------
7  |      a       |  Cleaning       |      1          |   Alex 
8  |      b       |  Driving        |      1          |   Alex
9  |      c       |  Writing        |      1          |   Alex

我想对上述查询应用NOT EXISTS查询:

SELECT s.id, s.service_measure 
FROM first_query
WHERE not exists (Select 1 
              from user_service_hist ush 
              where ush.service_id = s.id)

我的user_service_hist ush表格如下:

id | service_id
--------------------
1  | 7
2  | 8

基本上,第一个查询的结果应该只显示尚未添加到user_service_hist ush表的服务。

我很感激有关如何将这两个查询合并为一个语句的一些指示。

我希望我的结果如下:

id | service_type | service_measure | service_prov_id | service_prov_name
-------------------------------------------------------------------------
9  |      c       |  Writing        |      1          |   Alex

1 个答案:

答案 0 :(得分:2)

在这种情况下,只需使用where运算符将第二个查询的and子句添加到第一个查询:

SELECT s.id, st.service_type, s.service_measure, sp.id as `service_prov_id`,
sp.service_prov_name
from service s, service_prov_type_assign spta, service_prov_type_service_assign sptsa, 
service_type st, service_type_assign sta, service_provider sp 
WHERE sp.id = '3'
    AND spta.service_prov_id = sp.id
    AND sptsa.service_prov_type_id = spta.service_prov_type_id
    AND s.id = sptsa.service_id
    AND sta.service_id = s.id
    AND st.id = sta.service_type_id
    AND not exists (Select 1 
          from user_service_hist ush 
          where ush.service_id = s.id)

注意:我会使用显式连接语法而不是隐式连接语法来将连接条件与过滤条件分开。例如:

...
from service s
inner join service_prov_type_service_assign on s.id = sptsa.service_id
...

显然,您需要从s.id = sptsa.service_id子句中删除where条件。