表格中的問題是,對象可以是在四列Subject1 Subject2 Subject3 Subject4
的任何列,爲此,你可以使用IN
謂詞是這樣的:
WHERE 'Psyhcology' IN(Subject1, Subject2, Subject3, Subject4)
這樣完整的查詢將是:
SELECT
UserId,
UserName,
Year,
Form,
'Psyhcology' AS Subject
FROM tablename
WHERE Year = 13
AND Form = 'D'
AND userID IN(SELECT UserID
FROM tablname
WHERE 'Psychology' IN(Subject1, Subject2, Subject3, Subject4));
需要注意的是:該查詢會給你複製爲Name
行,因爲你必須用不同的ID的多個名稱:
╔═════════╦═══════════╦═══════╦═══════╦════════════╗
║ USERID ║ USERNAME ║ YEAR ║ FORM ║ SUBJECT ║
╠═════════╬═══════════╬═══════╬═══════╬════════════╣
║ 1 ║ John ║ 13 ║ D ║ Psyhcology ║
║ 2 ║ John ║ 13 ║ D ║ Psyhcology ║
║ 296 ║ Henry ║ 13 ║ D ║ Psyhcology ║
║ 297 ║ Henry ║ 13 ║ D ║ Psyhcology ║
╚═════════╩═══════════╩═══════╩═══════╩════════════╝
但是,如果你想獲得唯一的行,你必須選擇一個ID爲每個組的名稱,例如MIN(USerID)
:
SELECT
MIN(UserId) AS UserId,
UserName,
Year,
Form,
'Psyhcology' AS Subject
FROM users
WHERE Year = 13
AND Form = 'D'
AND userID IN(SELECT UserID
FROM users
WHERE 'Psychology' IN(Subject1,
Subject2,
Subject3,
Subject4))
GROUP BY Username, Year, Form, Subject;
這會給你:
╔═════════╦═══════════╦═══════╦═══════╦════════════╗
║ USERID ║ USERNAME ║ YEAR ║ FORM ║ SUBJECT ║
╠═════════╬═══════════╬═══════╬═══════╬════════════╣
║ 296 ║ Henry ║ 13 ║ D ║ Psyhcology ║
║ 1 ║ John ║ 13 ║ D ║ Psyhcology ║
╚═════════╩═══════════╩═══════╩═══════╩════════════╝
但是,我寧願normalize表代替,通過爲subjects
創建一個新表:
Subjects
:
SubjectId
PK,
SubjectName
。
那麼你的表格看起來像:
UserId
,
UserName
,
Year
,
Form
,
SubjectId
一個外鍵引用的對象表。
這樣可以更容易地查詢這兩個表。舉例來說,如果你要搜索誰採取特定主題的用戶,你可以簡單地連接兩個表:
SELECT
MIN(u.UserId) AS UserId,
u.Username,
u.Year,
u.Form,
s.Subjectname
FROM users AS u
INNER JOIN subjects AS s ON u.subjectId = s.subjectId
WHERE s.subjectname = 'Psyhcology'
AND u.Year = 13
AND u.Form = 'D'
GROUP BY u.Username, u.Year, u.Form, s.Subjectname;
這將給你相同的結果之前:
╔═════════╦═══════════╦═══════╦═══════╦═════════════╗
║ USERID ║ USERNAME ║ YEAR ║ FORM ║ SUBJECTNAME ║
╠═════════╬═══════════╬═══════╬═══════╬═════════════╣
║ 296 ║ Henry ║ 13 ║ D ║ Psyhcology ║
║ 1 ║ John ║ 13 ║ D ║ Psyhcology ║
╚═════════╩═══════════╩═══════╩═══════╩═════════════╝
這裏與修改後的表結構演示:
這是jdbc相關還是隻是一個SQL查詢? – PopoFibo