我有一个表,要求我使用两个行共享的唯一值将某些行配对。
例如在下表中;
+--------+----------+-----------+-----------+----------------+-------------+
| id | type | member | code | description | matching |
+--------+----------+-----------+-----------+----------------+-------------+
| 1000 |transfer | 552123 | SC120314 | From Gold | |
| 1001 |transfer | 552123 | SC120314 | To Platinum | |
| 1002 |transfer | 833612 | SC120314 | From silver | |
| 1003 |transfer | 833612 | SC120314 | To basic | |
| 1004 |transfer | 457114 | SC150314 | From Platinum | |
| 1005 |transfer | 457114 | SC150314 | To silver | |
| 1006 |transfer | 933276 | SC180314 | From Gold | |
| 1007 |transfer | 933276 | SC180314 | From To basic | |
+--------+----------+-----------+-----------+----------------+-------------+
基本上我需要的查询/例程是找到'成员'中值的行。每行匹配的列。然后看看'代码中的值是否为'找到的相同行的列也匹配。
如果两行的两列都匹配,则为匹配的'分配一个值。两行的列。对于两行,此值应该相同,并且仅对它们唯一。
唯一代码绝对可以是任何东西,只要它对匹配行是唯一的。是否有任何查询/例程可以执行此操作?
答案 0 :(得分:1)
我不确定我是否正确理解了这个问题,但是如果您想挑选并更新code
和member
列匹配的行并将matching
设置为某些每个相关行的唯一值,我相信这会起作用:
UPDATE <table> A
INNER JOIN (SELECT * FROM <table>) B ON
B.member = A.member && B.code = A.code && A.id <> B.id
SET A.matching = (A.id + B.id);
匹配值将设置为两行的id
列的总和。 注意 如果有两行以上的行可以匹配,则以这种方式更新matching
字段将无效。
对您的示例表运行上述查询将产生:
+------+----------+--------+----------+---------------+----------+
| id | type | member | code | description | matching |
+------+----------+--------+----------+---------------+----------+
| 1000 | transfer | 552123 | SC120314 | From Gold | 2001 |
| 1001 | transfer | 552123 | SC120314 | To Platinum | 2001 |
| 1002 | transfer | 833612 | SC120314 | From Silver | 2005 |
| 1003 | transfer | 833612 | SC120314 | To basic | 2005 |
| 1004 | transfer | 457114 | SC150314 | From Platinum | 2009 |
| 1005 | transfer | 457114 | SC150314 | To silver | 2009 |
| 1006 | transfer | 933276 | SC180314 | From Gold | 2013 |
| 1007 | transfer | 933276 | SC180314 | From To basic | 2013 |
+------+----------+--------+----------+---------------+----------+
答案 1 :(得分:0)
我可以给你一个简单的查询,告诉你什么可以做你需要的。
tst 是表格的名称。
SELECT *, COUNT( t2.id ) as matching FROM tst t LEFT JOIN tst t2 ON t2.member = t.member GROUP BY t.id