Mysql查询选择非成员

时间:2013-03-11 20:46:26

标签: mysql sql

我有两张桌子:

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 

但它不起作用。我做错了什么?

3 个答案:

答案 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;