而不是使用和/或總結命中:
SELECT *,
CASE WHEN 1_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_1,
CASE WHEN 2_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_2,
CASE WHEN 3_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_3,
CASE WHEN 4_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_4,
CASE WHEN 5_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_5,
CASE WHEN 6_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_6,
CASE WHEN 1_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 2_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 3_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 4_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 5_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 6_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
AS no_of_matches
FROM data
WHERE
(
CASE WHEN 1_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 2_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 3_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 4_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 5_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
+ CASE WHEN 6_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END
) in (4,5,6)
ORDER BY id ASC;
備用,使用嵌套查詢了一下漂亮:
SELECT a.*, a.match_1+a.match_2+a.match_3+a.match_4+a.match_5+a.match_6 AS no_of_matches
FROM (
SELECT *,
CASE WHEN 1_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_1,
CASE WHEN 2_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_2,
CASE WHEN 3_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_3,
CASE WHEN 4_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_4,
CASE WHEN 5_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_5,
CASE WHEN 6_column IN ('$a1a','$a2a','$a3a','$a4a','$a5a','$a6a') THEN 1 ELSE 0 END AS match_6
FROM data
) a
WHERE a.match_1+a.match_2+a.match_3+a.match_4+a.match_5+a.match_6 in (4,5,6)
ORDER BY id ASC;
這類問題有時是對症慘不忍睹的設計。 – Strawberry 2013-07-08 17:35:21