0

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

id, user_name, color1, color2, fruit1,fruit2

我只想在color1color2OR 时按 id 选择一行!fruit1,fruit2现在彼此相等。如果color1== color2OR fruit1==fruit2查询应该返回 0 行。如果color1<>color2fruit1==fruit2该行应该只返回id, user_name, color1,color2

谢谢

4

3 回答 3

0

我认为这应该很简单。

SELECT  id, user_name, color1, color2
FROM    tableName
WHERE   (color1 <> color2) AND (fruit1 = fruit2)
于 2013-03-18T02:30:44.033 回答
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
于 2013-03-18T02:31:52.173 回答
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

在此查询中,布尔值FALSEorTRUE被隐式​​转换为0or 1

因此,此查询仅在恰好匹配一种类型时才会产生行。

于 2013-03-18T02:32:41.843 回答