2

基本上,我想从 customers 表中获取所有未出现在 brochure_requests 表中的行。

SELECT *      
  FROM customers  JOIN  brochure_requests
    WHERE brochure_requests.first_name != customers.customer_first_name
    AND brochure_requests.last_name != customers.customer_last_name

该查询在参数为 = 时有效,但只要我运行一个 != 查询,程序 (HeidiSQL) 就会无限期挂起或直到我取消它。

4

3 回答 3

5

您在 brochure_requests 表中没有 customerID 吗?

如果你这样做,你可以这样做:

select * from customers 
where customerId not in (select customerId from brochure_requests)
于 2012-04-05T13:58:27.927 回答
4

使用NOT EXISTS,例如

SELECT *      
FROM customers 
WHERE NOT EXISTS (
    SELECT 1
    FROM   brochure_requests
    WHERE  brochure_requests.first_name = customers.customer_first_name
    AND    brochure_requests.last_name = customers.customer_last_name)

我还建议在brochure_requests.first_nameandbrochure_requests.last_name字段上添加索引以提高性能。

于 2012-04-05T13:57:31.000 回答
3
SELECT 
    *
FROM 
    customers  
    LEFT JOIN brochure_requests
        ON brochure_requests.first_name = customers.customer_first_name
        AND brochure_requests.last_name = customers.customer_last_name

WHERE 
    brochure_requests.first_name IS NULL

此外,请考虑通过将 CustomerID 添加为外键来规范化您的数据库,brochure_requests而不是复制名字和姓氏。

于 2012-04-05T13:58:24.853 回答