1

我有几张桌子:

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    

我设法仅输出用户输入的专业知识,而不是同一 sig 中的所有专业知识。

提前致谢

4

2 回答 2

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(至少对于此类复杂查询)。

于 2012-05-29T19:39:33.370 回答
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
   )
于 2012-05-29T19:44:43.323 回答