最简单的方法是扩展逻辑并包括两种情况:
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