我不知道是否可能,但我正在尝试SELECT
不匹配列,假设我有一个包含列的表:
id
,user_name
,color1
,color2
,fruit1
,fruit2
我想只在color1
和color2
OR时按ID选择行! fruit1
,fruit2
现在彼此相等。如果color1
== color2
或fruit1
== fruit2
,则查询应返回0行。如果color1
<> color2
和fruit1
== fruit2
该行应仅返回id
,user_name
,color1
,color2
谢谢
答案 0 :(得分:0)
我认为这应该非常简单。
SELECT id, user_name, color1, color2
FROM tableName
WHERE (color1 <> color2) AND (fruit1 = fruit2)
答案 1 :(得分:0)
最简单的方法是扩展逻辑并包括两种情况:
SELECT id, user_name, color1, color2, fruit1, fruit2
FROM myTable
WHERE (color1 <> color2 AND fruit1 = fruit2)
OR (color1 = color2 AND fruit1 <> fruit2)
从你的评论中,你将不得不尝试一些更复杂的东西:
SELECT nonmatching.id, user_name, prop_name, value1, value2
FROM
(
SELECT id, user_name, prop_name, value1, value2
FROM
(
SELECT id, user_name, 'color' AS prop_name,
color1 AS value1, color2 AS value2
FROM myTable
UNION ALL
SELECT id, user_name, 'fruit' AS prop_name,
fruit1 AS value1, fruit2 AS value2
FROM myTable
) propertyExpanded
WHERE value1 <> value2
) nonmatching
例如,如果您只想返回一个不匹配的行,则可以添加以下内容:
INNER JOIN
(
SELECT id, COUNT(1) AS mismatchCount = 1
FROM
(
SELECT id, user_name, 'color' AS prop_name,
color1 AS value1, color2 AS value2
FROM myTable
UNION ALL
SELECT id, user_name, 'fruit' AS prop_name,
fruit1 AS value1, fruit2 AS value2
FROM myTable
) propertyExpanded
WHERE value1 <> value2
GROUP BY id
) nonmatchingCount ON nonmatching.id = nonmatchingCount.id
WHERE nonmatchingCount.mismatchCount = 1
答案 2 :(得分:0)
这应该有效:
SELECT id,
user_name,
color1,
color2
FROM mytable
WHERE (color1 = color2) != (fruit1 = fruit2)
这里的诀窍是我将比较结果作为布尔值进行比较。
这种方法可以推广到支持两种以上的精确单一数据匹配。也就是说,你可以通过计算这样的匹配来使用类似的技巧:
SELECT * FROM mytable
WHERE (color1 = color2)
+ (fruit1 = fruit2)
+ ...
+ (kind1 = kind2)
= 1
在此查询中,布尔FALSE
或TRUE
会隐式转换为0
或1
。
因此,只有当恰好一个种匹配时,此查询才会生成行。