我有以下表
userid | Field1 | Field2 | Field3
1 | S | M | M
2 | M | A | B
现在我有一套(S,M,A)。
我想给2分。 Field1,Field3,Fields这三个包含给定集合中的任何一个值。如果任何一个Field匹配,则该点将为6.
例如输出应为
userid | Field1 | Field2 | Field3 | points
1 | S | M | M | 6
2 | M | A | B | 4
我使用了Followig Query但它没有返回任何值
SELECT @hqp,
UserId
FROM (SELECT @hqp := 0,
IF( Field1 IN ('S','M','A'), @hqp := @hqp +2, @hqp),
IF( Field2 IN ('S','M','A'), @hqp := @hqp +2, @hqp),
IF( Field3 IN ('S','M','A'), @hqp = @hqp +2, @hqp),
@prev:=A.user_id as UserId
FROM users as A
JOIN (SELECT @hqp := 0, @prev:=0) as B) as M
但它为每一行返回@hpq
为0。任何人都可以提供帮助。
答案 0 :(得分:2)
尝试这种方式:
SELECT userid,
Field1,
Field2,
Field3,
(IF(Field1 IN ('S','M','A'),2,0)+
IF(Field2 IN ('S','M','A'),2,0)+
IF(Field3 IN ('S','M','A'),2,0) ) points
FROM users
答案 1 :(得分:0)
这种问题往往是设计不良的症状,所以看看正常化。
但是,以下内容将起作用......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(userid INT NOT NULL PRIMARY KEY
,Field1 CHAR(1) NOT NULL
,Field2 CHAR(1) NOT NULL
,Field3 CHAR(1) NOT NULL
);
INSERT INTO my_table VALUES
(1,'S','M','M'),
(2,'M','A','B');
SELECT userid
, SUM(f IN ('S','M','A'))*2 points
FROM
( SELECT userid,field1 f FROM my_table UNION ALL SELECT userid,field2 FROM my_table UNION ALL SELECT userid,field3 FROM my_table ) x
GROUP
BY userid;
+--------+--------+
| userid | points |
+--------+--------+
| 1 | 6 |
| 2 | 4 |
+--------+--------+