我有一张名为技能的表:
我想搜索具有2年以上经验的技能java的用户,以及具有1年以上经验的技能jquery。
我试过了:
{{1}}
预期结果为15.但查询返回空结果集。
任何帮助将不胜感激。提前谢谢!
where子句中的条件数可能会有所不同。
答案 0 :(得分:2)
这是你的WHERE
- 条款:
WHERE `skill` = 'java' AND `experience` > 2
AND `skill` = 'jquery' AND `experience` > 1
这意味着,您选择的元素必须符合以下条件:
skill
='java'experience
> 2 skill
='jquery'experience
> 1 这将始终返回一个空结果集,因为表中单个记录的技能值永远不能等于'java'并且等于'jquery'。
解决问题的最佳方法是使用表连接:
SELECT S1.userid
FROM skills As S1
INNER JOIN skills As S2
ON S1.userid = S2.userid
WHERE S1.skill = 'java' AND S1.experience > 2
AND S2.skill = 'jquery' AND S2.experience > 1
如果您想搜索其他技能,只需为每个要添加的技能添加一个联接:
SELECT S1.userid
FROM skills As S1
INNER JOIN skills As S2
ON S1.userid = S2.userid
INNER JOIN skills As S3
ON S1.userid = S3.userid
WHERE S1.skill = 'java' AND S1.experience > 2
AND S2.skill = 'jquery' AND S2.experience > 1
AND S3.skill = 'PHP' AND S3.experience > 1
答案 1 :(得分:0)
试试这个:
SELECT userid
FROM skills
WHERE (skill = 'java' AND experience > 2)
OR
(skill = 'jquery' AND experience > 1)
GROUP BY userid
HAVING COUNT(DISTINCT skill) = 2
WHERE
子句谓词返回具有任何技能(或两者)的用户。 HAVING
子句确保只返回具有这两种技能的用户。