[英]SQL Query Syntax Error using select & <> with 2 columns
I got a table with 2 columns here. 我在这里有2列的表格。
| column1 | column2 |
| A | 1 |
| B | 1 |
| C | 2 |
| D | 1 |
I'm trying to execute a SELECT query that: Selects a value FROM Column 2 WHILE Column 2 doesn't have the same value in a row which has Column 1 = "A" 我试图执行一个SELECT查询:从第2列中选择一个值,而第2列在具有Column 1 =“ A”的行中没有相同的值
SELECT column2 from mytable and column2 <> (SELECT * FROM mytable where column1 = 'A');
Basically I'm trying to execute a query that returns column1 values only when column2 is valued at "2" here. 基本上,我试图执行一个查询,该查询仅在此处column2的值为“ 2”时才返回column1的值。 But the project I'm making will be having column2 values random so I should use only columns names
但是我正在做的项目将把column2值随机化,所以我应该只使用列名
Sorry if that's too confusing! 抱歉,这太令人困惑了!
use corelated subquery 使用相关子查询
select t1.* from mytable t1
where not exists ( select 1 from mytable t2 where t2.column2=t1.column2 and column1='A')
or use not in
或
not in
select t1.* from table_name t1 where t1.column2 not in ( select column2 from table_name where column1='A')
The subquery of your query returns multiple values. 您的查询子查询返回多个值。 So you have to use
NOT IN
instead of <>
: 因此,您必须使用
NOT IN
代替<>
:
SELECT column2
FROM mytable
WHERE column2 NOT IN (SELECT column2 FROM mytable WHERE column1 = 'A');
You could also use a join
, for example: 您还可以使用
join
,例如:
select t1.column2
from mytable t1 left join
(select distinct t2.column2 from mytable t2 where t2.column1='A') t3 on t1.column2=t3.column2
where t3.column2 is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.