用复合键连接表两次

时间:2012-12-06 15:17:39

标签: mysql sql database join trac

如果表ticket包含主键id,表ticket_custom包含复合键ticket,name,我该如何加入id = ticket and name=X and id = ticket and name=Y

ticket_custom允许票证表扩展,它包含字段ticket,name,value

我可以进行一次加入:

SELECT id, summary, owner, ticket_custom.value
FROM ticket
INNER JOIN ticket_custom
ON id=ticket_custom.ticket AND ticket_custom.name='X'

我需要类似的东西:

SELECT id, summary, owner, ticket_custom.value, ticket_custom.value
FROM ticket
INNER JOIN ticket_custom
ON id=ticket_custom.ticket AND ticket_custom.name='X' AND ticket_custom.name='Y'

第一个ticket_custom.valueid,x的值,第二个是id,y

3 个答案:

答案 0 :(得分:4)

如果我理解正确,这就是你要找的东西:

SELECT id, summary, owner, c1.value, c2.value
FROM ticket t
INNER JOIN ticket_custom c1  ON t.id = c1.ticket AND c1.name = 'X'
INNER JOIN ticket_custom c2  ON t.id = c2.ticket AND c2.name = 'Y'

答案 1 :(得分:0)

我这应该做的伎俩:

SELECT id, summary, owner, ticket_custom.value, ticket_custom.value
FROM ticket
INNER JOIN ticket_custom
ON ticket.id=ticket_custom.ticket
WHERE (ticket_custom.name='X' OR ticket_custom.name='Y')

答案 2 :(得分:0)

<强>也许

SELECT id, summary, owner, ticket_custom.value, ticket_custom.value
FROM ticket
INNER JOIN ticket_custom
ON id=ticket_custom.ticket AND ticket_custom.name='X' 
    OR id=ticket_custom.ticket AND ticket_custom.name='Y'