将 NOT EXISTS 查询和普通的 SELECT 查询组合成一个语句

Combining NOT EXISTS query and a normal SELECT query into a single statement

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

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 ushtable看起来如下:

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

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

对于如何将这 2 个查询组合成一个语句的一些指示,我将不胜感激。

我希望我的结果如下所示:

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

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

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
...

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