如何离开外连接2表?
class Person {
String firstName
String lastName
String gender
//static hasMany = [votes: Vote]
static mapping = {
version false
}
static constrains = {
}
}
class Vote {
Person voter;
Person subject;
static mapping = {
version false
}
static constraints = {
voter nullable: false
subject nullable: false
}
}
我需要让每个未经投票的人为特定的人。 让我说1人投票给5人中的3人,我需要另外2人他没有投票为他出现。 查询应该如何?
修改
def personInstance1 = new Person(firstName: "Antonio", lastName: "Vivaldi", gender: "m")
def personInstance2 = new Person(firstName: "Dennis", lastName: "Rodman", gender: "m")
def personInstance3 = new Person(firstName: "Marc", lastName: "Oh", gender: "m")
def personInstance4 = new Person(firstName: "Gudrun", lastName: "Graublume", gender: "w")
def personInstance5 = new Person(firstName: "Hilde", lastName: "Feuerhorn", gender: "w")
def personInstance6 = new Person(firstName: "Mandy", lastName: "Muller", gender: "w")
personInstance1.save()
personInstance2.save()
personInstance3.save()
personInstance4.save()
personInstance5.save()
personInstance6.save()
def voteInstance1 = new Vote(voter: personInstance1, subject: personInstance2)
def voteInstance2 = new Vote(voter: personInstance1, subject: personInstance3)
def voteInstance3 = new Vote(voter: personInstance1, subject: personInstance4)
def voteInstance4 = new Vote(voter: personInstance1, subject: personInstance5)
def voteInstance5 = new Vote(voter: personInstance2, subject: personInstance1)
voteInstance1.save()
voteInstance2.save()
voteInstance3.save()
voteInstance4.save()
voteInstance5.save()
这是我的grails bootstrap文件,Antonio和Dennis已投票,每个人都需要出示他们没有投票的人员名单。
修改 这样我似乎得到丹尼斯的结果,因为他只投了一次, 但如果我把v.voter_id = 1, 为了得到安东尼奥的结果,结果是根据他做了多少票而加倍。
SELECT first_name FROM vote as v
LEFT OUTER JOIN person as p
ON v.subject_id != p.id AND v.voter_id = 2
WHERE p.id IS NOT NULL
答案 0 :(得分:1)
试试这个:
SELECT * FROM Person P
WHERE NOT EXISTS(
SELECT 'Vote' FROM Vote V
WHERE V.subject = P
)
通过这种方式,您可以提取所有没有投票的人
修改强>
在SQL中,您可以通过以下方式检索矩阵:
CREATE TABLE #person (nome varchar(30))
CREATE TABLE #vote (votante varchar(30), candidato varchar(30))
INSERT INTO #person values
('Antonio Vivaldi'),
('Dennis Rodman'),
('Marc Oh'),
('Gudrun Graublume'),
('Hilde Feuerhorn'),
('Mandy Muller')
INSERT INTO #vote values
('Antonio Vivaldi', 'Dennis Rodman'),
('Antonio Vivaldi', 'Marc Oh'),
('Antonio Vivaldi', 'Gudrun Graublume'),
('Antonio Vivaldi', 'Hilde Feuerhorn'),
('Dennis Rodman', 'Antonio Vivaldi')
SELECT *
FROM #person p
CROSS JOIN #person c
WHERE NOT EXISTS(
SELECT 'X'
FROM #vote v
WHERE v.votante = p.nome
AND v.candidato = c.nome
)
AND p.nome <> c.nome
ORDER BY p.nome