[英]MySql AND operator against single column (comparison between two rows of one column)
I have been trying to execute this query but it's not working. 我一直在尝试执行此查询,但无法正常工作。
Would appreciate if anyone helps; 如果有人帮助,将不胜感激;
SELECT DISTINCT(fld_tech_id)
FROM tbl_tech_properties
WHERE fld_tech_category_value_id = 236
AND fld_tech_category_value_id = 234
It's impossible for your WHERE
condition to ever match because it is tested for each row in the table and no single row can have fld_tech_category_value_id
equal to both 234 and 236 at the same time. 您的
WHERE
条件不可能匹配,因为它已针对表中的每一行进行了测试,并且任何一行都不能同时具有等于234和236的fld_tech_category_value_id
。 Instead you should group by fld_tech_id and check that your group contains two rows. 相反,您应该按fld_tech_id分组,并检查您的组是否包含两行。
SELECT fld_tech_id
FROM tbl_tech_properties
WHERE fld_tech_category_value_id IN (234, 236)
GROUP BY fld_tech_id
HAVING COUNT(DISTINCT fld_tech_category_value_id) = 2
Why don't you just use
你为什么不只用
SELECT DISTINCT fld_tech_id FROM tbl_tech_properties WHERE fld_tech_category_value_id IN (236,234) ;
Results based on sample data on the reference:
基于参考样本数据的结果:
sample table: 样品表:
FLD_TECH_ID FLD_TECH_CATEGORY_VALUE_ID
1 234
2 256
3 236
3 250
2 226
3 216
1 240
1 236
Results:
结果:
FLD_TECH_ID 1 3
REFERENCE
SQLFIDDLE
参考
SQLFIDDLE
A solution that works: 有效的解决方案:
SELECT DISTINCT fld_tech_id
FROM tbl_tech_properties AS t
WHERE EXISTS
( SELECT *
FROM tbl_tech_properties AS t1
WHERE t1.fld_tech_id = t.fld_tech_id
AND t1.fld_tech_category_value_id = 236
)
AND EXISTS
( SELECT *
FROM tbl_tech_properties AS t2
WHERE t2.fld_tech_id = t.fld_tech_id
AND t2.fld_tech_category_value_id = 234
) ;
Referernce SQL-Fiddle test 2 Referernce SQL小提琴测试2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.