MySQL查询只选择不匹配的对

时间:2013-03-18 02:28:41

标签: mysql

我不知道是否可能,但我正在尝试SELECT不匹配列,假设我有一个包含列的表:

iduser_namecolor1color2fruit1fruit2

我想只在color1color2 OR时按ID选择行! fruit1fruit2现在彼此相等。如果color1 == color2fruit1 == fruit2,则查询应返回0行。如果color1<> color2fruit1 == fruit2该行应仅返回iduser_namecolor1color2

谢谢

3 个答案:

答案 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

在此查询中,布尔FALSETRUE会隐式转换为01

因此,只有当恰好一个种匹配时,此查询才会生成行。