SQL将列的值与其他列的所有值匹配

时间:2016-03-17 19:12:39

标签: mysql sql

我只有一个表:产品

ID | Product Name | Code 1 | Code 2 | Code 3
********************************************
1  |    Phone1    |   MM   |   DD   |  
2  |    Phone2    |   DD   |        |   EE
3  |    Phone3    |   MM   |   ZZ   |   EE
4  |    Phone4    |   XX   |        |

我想:

  

选择其中一个代码与其中一个匹配的所有手机    Phone1 的代码。

换句话说:

  

如果Phone1 [Code 1] = Phone2 [Code 1]或Phone1 [Code 1] = Phone2 [Code 2]或Phone1 [Code 1] = Phone2 [Code 3]或Phone1 [Code 1] = Phone3 [Code 1] ] ......等等。

将每个 Phone1列的值与每个 PhoneX列的值进行比较。 3x3条件=总共9个。

所以它应该返回:Phone2和Phone3(它应该跳过空=空的匹配)。

我的尝试(自我加入) - 我是新手,并且无法做到这一点:

SELECT `a.Product Name`
FROM products a, products b
WHERE 
(`a.Code 1` = `b.Code 1`) OR 
(`a.Code 1` = `b.Code 2`) OR   
(`a.Code   1` = `b.Code 3`) OR 
(`a.Code 2` = `b.Code 1`) OR 
(`a.Code 2` = `b.Code 2`) OR 
(`a.Code 2` = `b.Code 3`) OR
(`a.Code 3` = `b.Code 1`) OR
(`a.Code 3` = `b.Code 2`) OR
(`a.Code 3` = `b.Code 3`)
AND `a.Product Name` = "Phone1";

提前谢谢!

2 个答案:

答案 0 :(得分:2)

也许是这样的。

SELECT  p.*
FROM    Products p
        JOIN Products p1 ON p1.`Product Name` = 'Phone1'
                            AND (p1.`Code 1` IN (p.`Code 1`,p.`Code 2`,p.`Code 3`)
                                 OR p1.`Code 2` IN (p.`Code 1`,p.`Code 2`,p.`Code 3`)
                                 OR p1.`Code 3` IN (p.`Code 1`,p.`Code 2`,p.`Code 3`))
WHERE   p.`Product Name` <> 'Phone1'

SQL Fiddle Demo

答案 1 :(得分:0)

应该是这个查询

select `a.Product Name` from products as a
left join products as b on  a.`a.Code 1` = `b.Code 2`
left join prodcuts as c on  a.`a.Code 1` = `c.Code 3`
where `a.Product Name` = "Phone1";