关于选择查询,一个表多个结果

时间:2014-12-26 13:57:43

标签: sql select

我在问我的问题之前搜查过:

我有两张桌子。

信息

no    | name
1     | david
2     | kang

info_kill

no   | staffno | skillno
------------------------
1    |    1    |    1
2    |    2    |    1
3    |    2    |    2
4    |    2    |    3
staffno表中的

info_skillno表中的info是外键。

我想得到:

  1. name包含' ka'
  2. skillno 1,2,3。
  3. 所以,这是我的sql,

    SELECT a.NAME
    FROM   (SELECT no,
                   NAME
            FROM   info
            WHERE  NAME LIKE '%ka%') AS a
           INNER JOIN info_skill AS b
                   ON a.no = b.staffno
           INNER JOIN info_skill AS c
                   ON a.no = c.staffno
           INNER JOIN info_skill AS d
                   ON a.no = d.staffno
    WHERE  b.skillno = '1'
           AND c.skillno = '2'
           AND d.skillno = '3' 
    

    我想知道的是这部分。

           INNER JOIN info_skill AS b
                   ON a.no = b.staffno
           INNER JOIN info_skill AS c
                   ON a.no = c.staffno
           INNER JOIN info_skill AS d
                   ON a.no = d.staffno
    WHERE  b.skillno = '1'
           AND c.skillno = '2'
           AND d.skillno = '3' 
    

    还有其他办法吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT I.name
FROM info I
    JOIN info_skill S
         ON I.no = S.staffno
WHERE I.name LIKE'%ka%" AND
      S.skillno=1 OR
      S.skillno=2 OR
      S.skillno=3

这意味着:

  • 您加入外键后的两个表
  • 然后使用LIKE %ka%
  • 搜索包含 ka 字词的任何名称
  • 现在,您需要检查skillno是否等于1,2或3

如果这不是您所需要的,那么请通过解释您正在寻找的内容来更清楚地说明您的问题。

答案 1 :(得分:1)

select a.name 
from info a
inner join info_skill as b on a.no = b.staffno
where b.skillno in (1,2,3)
and name like '%ka%'
group by a.name
having count(distinct b.skillno) = 3

SQLFiddle demo