SQL从父类型检索数据

时间:2012-05-21 21:44:46

标签: sql inner-join

我有几张桌子:

lecturer(id,name,email)
- 1,john,john@abc.com
- 2,andy,andy@abc.com
- 3,kyle,kyle@abc.com
- 4,allen,allen@abc.com

sig(id,name)
- s1, Multimedia
- s2, Business IT

expertise(id, description); 
- e1, Gaming
- e2, Graphic
- e3, Multimedia System
- e4, E-Business

lecturer_has_expertise(lecturer.id,expertise.id)
- 1, e1
- 2, e2
- 3, e4
- 4, e1

lecturer_has_sig (lecturer.id,sig.id)
- 1, s1
- 2, s1
- 3, s2

sig_has_expertise(sig.id,expertise.id)
- s1, e1
- s1, e2
- s1, e3
- s2, e4

这是我想要显示的输出:

Lecturer's Name, Email, Expertise

基本上,当用户在文本框中输入关键字,例如:游戏时,它会显示哪位讲师的专业知识是游戏,并且由于游戏位于多媒体下,所以有关所有人的数据还将展示多媒体的讲师。例如:

Name   Email            Expertise
John   john@abc.com     Gaming
Allen  allen@abc.com    Gaming
Andy   andy@abc.com     Graphic    

我设法只输出用户输入的专业知识,但不输出同一信号中的所有专业知识。

提前致谢

2 个答案:

答案 0 :(得分:1)

这有效(至少对你的样本而言)并在MySQL上进行测试。但它是纯SQL,所以它应该适用于大多数数据库。

SELECT lc.name, lc.email, ex.description
FROM lecturer lc 
INNER JOIN lecturer_has_expertise lhc ON lc.id = lhc.lcId
INNER JOIN expertise ex ON ex.id = lhc.exId
WHERE ex.description = 'Gaming'

UNION

SELECT lc.name, lc.email, ex2.description
FROM 
(SELECT she.sigId FROM expertise ex 
INNER JOIN sig_has_expertise she ON she.exId = ex.id
WHERE ex.description = 'Gaming') sigex
INNER JOIN sig_has_expertise she2 ON sigex.sigId = she2.sigId
INNER JOIN expertise ex2 ON she2.exId = ex2.id
INNER JOIN lecturer_has_expertise lhc ON ex2.id = lhc.exId
INNER JOIN lecturer lc ON lhc.lcId = lc.id

下次请提供样本数据的DDL(至少对于此类复杂查询)。

答案 1 :(得分:1)

所以基本上你想要归还每个

的老师
  • 具有指定的专业知识

  • 属于具有指定专业知识的群体。

以上是SQL中的翻译方式:

SELECT
  l.name,
  l.email,
  e.description AS expertise
FROM lecturer_has_expertise le
  INNER JOIN lecturer l ON l.id = le.lecturer_id
  INNER JOIN expertise e ON e.id = le.expertise_id
WHERE e.description = @InputExpertise
   OR EXISTS (
     SELECT *
     FROM lecturer_has_sig ls
       INNER JOIN sig_has_expertise se ON ls.sig_id = se.sig_id
       INNER JOIN expertise e ON e.id = se.expertise_id
     WHERE e.description = @InputExpertise
       AND ls.lecturer_id = le.lecturer_id
   )