如何编写SQL查询

时间:2017-08-18 12:47:37

标签: mysql sql

我有3张桌子

质量

id    name
----------
 1    bold
 2    Frank
 3    Quite
 4    friendly

学生

id name
---------
 1  A
 2  B
 3  C

StudentQuality

id  fk_qual  fk_stud
 1   1        1
 2   2        1
 3   1        2
 4   2        2
 5   3        2
 6   1        3
 7   2        3
 8   3        3
 9   4        3

这些是我的表格。我如何让那些大胆,坦诚和相当的学生。 如果我使用IN操作,我会得到所有3名学生,我只需要2名学生 如果我使用大胆,坦白,我应该得到所有3名学生 如果我使用大胆,坦诚,相当友好,我应该得到所有1名学生 那么如何查询。

3 个答案:

答案 0 :(得分:1)

你可以这样做:

  1. 声明一个表变量,保存您正在搜索的值
  2. 选择数据并使用表变量作为INNER JOIN的条件并计算表变量的值并将它们与质量值进行比较
  3. 像:

    DECLARE  @qualities table(qname  varchar(100));
    INSERT INTO   @qualities   
           VALUES ('bold'),('Frank'),('Quite');
    
           SELECT S.name
             FROM Student S
       INNER JOIN StudentQuality SQ
               ON S.id = SQ.fk_stud
       INNER JOIN Quality Q
               ON SQ.fk_qual = Q.id
              AND Q.name in (SELECT qname FROM @qualities)          
          GROUP BY S.name
          HAVING count(*) = (SELECT COUNT(qname) FROM @qualities)  
    

答案 1 :(得分:0)

SELECT *
FROM Student
WHERE id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('bold')
)
INTERSECT
SELECT *
FROM Student
WHERE id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('frank')
)
INTERSECT
SELECT *
FROM Student
WHERE id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('quite')
)

或没有INTERSECT

SELECT *
FROM Student
WHERE id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('bold')
) and id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('frank')
) and id IN
(
  SELECT fk_stud 
  FROM StudentQuality sq
  JOIN Quality q ON sq.fk_qual = q.id
  WHERE q.name IN ('quite')
)

答案 2 :(得分:0)

另一种变化

SELECT s.id,min(s.name) studentname FROM student s
INNER JOIN (studentquality sq INNER JOIN quality q ON q.id=sq.fk_qual)
ON sq.fk_stud=s.id WHERE q.name in ('bold','frank','quite') group by s.id
having length(group_concat(q.name))=length(concat('bold,','frank,','quite'));

SELECT s.id,min(s.name) studentname, (group_concat(q.name)) qname FROM student s
INNER JOIN (studentquality sq INNER JOIN quality q ON q.id=sq.fk_qual)
ON sq.fk_stud=s.id WHERE q.name in ('bold','frank','quite') group by s.id
having length(qname)=length(concat('bold,','frank,','quite'));