MYSQL选择所有不等于某个值的项
我在一个等式上有点困难,我在这里似乎无法理解或找到。我正在努力做到以下几点:MYSQL选择所有不等于某个值的项,mysql,Mysql,我在一个等式上有点困难,我在这里似乎无法理解或找到。我正在努力做到以下几点: SELECT productname FROM products p, teamproducts tp WHERE teamcode = teamcode1 AND p.productid != tp.productid 我有两张桌子,产品和团队产品。这里的外键是productid。我正在尝试从products表中选择尚未注册到teamproducts表的产品。我还在teamproducts中使用一个team
SELECT productname FROM products p, teamproducts tp WHERE teamcode = teamcode1 AND p.productid != tp.productid
我有两张桌子,产品和团队产品。这里的外键是productid。我正在尝试从products表中选择尚未注册到teamproducts表的产品。我还在teamproducts中使用一个teamcode。下面是一个例子
产品表(productid | productname)
1001 |产品1
1002 |产品2
1003 |产品3
1004 |产品4
1005 |产品5
等
团队产品表(团队代码|产品ID)
团队代码1 | 1001
团队代码1 | 1002
我要做的是选择所有不在teamproducts页面中的产品(因此在本例中为product 3等)
我试过以下方法
SELECT productname FROM products p, teamproducts tp WHERE teamcode = teamcode1 AND p.productid != tp.productid
和其他的变化,我已经看到了,但没有提出正确的路线。请提供任何帮助。您要查找的是
左连接
,还有一个额外的条件可以从右表中消除空结果:
SELECT * FROM products
LEFT JOIN teamproducts USING (productid)
WHERE teamproducts.productid IS NULL; -- Add other conditions as needed
编辑添加“团队代码”条件:
SELECT * FROM products
LEFT JOIN teamproducts USING (productid)
WHERE teamproducts.productid IS NULL
AND teamproducts.teamcode = 'teamcode1'; -- Add other conditions as needed
更多关于JOIN和不同类型的it的信息:未经测试,但我认为这应该可以完成这项工作
SELECT products.productname
FROM products
LEFT JOIN teamproducts
ON teamproducts.teamcode = 'teamcode1'
AND teamproducts.productid = products.productid
WHERE teamproducts.productid IS NULL;
我认为您必须在引号之间编写
teamcode1
。
大概是这样的:
SELECT productname FROM products p, teamproducts tp WHERE teamcode = 'teamcode1' AND p.productid != tp.productid
可以使用not in子句
select * from products
where id not in (select productid from teamproduct);
由于subselect,MySQL无法像使用
左连接那样优化查询,这是有风险的。在我尝试添加teamcode参数之前,这是有效的,然后我不会得到任何结果。有什么建议吗?我编辑了答案以添加teamcode的条件。