我有一张这样的表:
ID | GenEx | CodeName | Desc
----------------------------
1 | Cipro | Dolvo |
2 | Ludavil | Ymir |
3 | Cipro | Alpha |
我的查询是这样的:
SELECT GenEx, GROUP_CONCAT(CodeName) AS Code
FROM Drugs D
WHERE `CodeName` IN ('Alpha')
GROUP BY GenEx;
我想要的结果是:
| Genex | Code |
+-------+-------------+
| Cipro | Dolvo,Alpha |
我得到的结果是:
| Genex | Code |
+-------+-------------+
| Cipro | Alpha,Alpha |
WHERE IN()
子句使GROUP_CONCAT
替换返回的任何内容以匹配该限制集。只要包含Alpha
,我怎样才能使其与该集合之外的代码匹配?
答案 0 :(得分:2)
我首先会编写一个子查询来获取哪个genex具有alpha代码:
SELECT DISTINCT genex
FROM drugs
WHERE codeName = 'Alpha';
然后,您可以将其用作IN
子句,因此它只包含将在组连续列表中包含Alpha的genex:
SELECT genex, GROUP_CONCAT(code_name)
FROM drugs
WHERE genex IN (
SELECT DISTINCT genex
FROM drugs
WHERE codeName = 'Alpha')
GROUP BY genex;
修改强>
关于子查询的小注,如果您想要检查多行代码,您仍然可以将WHERE =
替换为IN
:
SELECT DISTINCT genex
FROM drugs
WHERE codeName IN ('Alpha');
以下是SQL Fiddle示例。
答案 1 :(得分:1)
如果您不想使用子查询(无论出于何种原因),您可以尝试这样做:
SELECT GenEx, GROUP_CONCAT(CodeName) AS Code
FROM Drugs D
GROUP BY GenEx
HAVING 'Alpha' REGEXP GROUP_CONCAT(CodeName SEPARATOR '|');
或:
SELECT GenEx, GROUP_CONCAT(CodeName) AS Code
FROM Drugs D
GROUP BY GenEx
HAVING CONCAT(',',GROUP_CONCAT(CodeName),',') LIKE '%,Alpha,%';
但是子查询几乎肯定会比上面两个查询中的任何一个更有效。