我有两张桌子:
Customers:
- ID
- NAME
Modulemembers:
- ID
- customer_id
- enabled
我使用它来为某些客户启用我的网站的功能。 我有一个表单,网站的管理员可以为客户添加模块,所以我需要一个查询,查找不是modulemembers表成员的客户。
我做到了:
SELECT customers.id,
customers.name
FROM customers,
modulemembers
WHERE customers_id != modulemembers.cust_id
ORDER BY customers.name
但它不起作用。我做错了什么?
答案 0 :(得分:4)
您可以在NOT EXISTS
子句中使用WHERE
来获得结果:
SELECT c.id,
c.name
FROM customers c
WHERE not exists (select customer_id
from modulemembers m
where c.id = m.customer_id)
order by c.name
答案 1 :(得分:2)
您可以使用LEFT OUTER JOIN
并根据NULLs
进行过滤。下面的查询将从customers
表和modulemembers
表中提取所有结果。如果modulemembers
表中没有匹配项,则custid
将为NULL
。
SELECT c.id, c.name
FROM customers c
LEFT OUTER JOIN modulemembers m ON c.customers_id = m.cust_id
WHERE m.custid IS NULL
ORDER BY c.name
答案 2 :(得分:0)
尝试这样的事情:
SELECT c.ID AS customerId,
c.NAME AS fullName,
m.ID AS memberId
FROM Customers AS c
LEFT JOIN Modulemembers AS m ON m.customer_id = c.ID
WHERE m.ID IS NULL;