用户案例或子查询?

时间:2014-07-19 23:04:58

标签: mysql

我有3个表:ticket,tickets_users和users。我的问题是在users表中我有两种类型的用户:请求者和解算器:类型1和2。 我想选择票证,请求者(如果有的话,可以是多个)和解算器(如果有的话,可以是多个)。

我正在思考以下几点:

SELECT 
    t.id, t.description, 
    (u.id where u.type = 1) AS requester, 
    (u.id where u.type = 2)  AS solver
FROM 
    tickets t
INNER JOIN 
    tickets_users tu ON t.id = tu.ticket_id
INNER JOIN 
    users u ON tu.user_id = u.id

显然这不起作用。

表格如下:

门票:

ID       Description    
1        Description 1 
2        Description 2 

Tickets_users

ID        Ticket_ID  User_id   Type 
1         3          4         1
2         5          8         2

用户

ID        Name
1         John
2         Mary 

谢谢,

与此同时,我认为我在join子句中使用子查询找到了一个解决方案,但对我来说它看起来很简陋:

SELECT 
    t.id, t.name AS ticket_name, type1.users_id AS requester, 
    type2.users_id AS solver
FROM 
    tickets t
INNER JOIN 
    (SELECT users_id, tickets_id 
     FROM tickets_users 
     WHERE TYPE = 1) type1 ON t.id = type1.tickets_id
INNER JOIN 
    (SELECT users_id, tickets_id 
     FROM tickets_users 
     WHERE TYPE = 2) type2 ON t.id = type2.tickets_id

1 个答案:

答案 0 :(得分:0)

应该是这样的。

SELECT 
    t.id, t.description, u.id, userType
    CASE WHEN u.type = 1 THEN 'requester' ELSE 'solver' END
FROM 
    tickets t
    INNER JOIN tickets_users tu ON t.id = tu.ticket_id
    INNER JOIN users u ON tu.user_id = u.id

如果上面的示例不起作用,请提供sqlfiddle。

使用加入,

SELECT 
    t.id, t.description, requesters.id, solvers.id
FROM 
    tickets t
    INNER JOIN tickets_users tu ON t.id = tu.ticket_id
    LEFT JOIN users requesters ON (tu.user_id = requesters.id AND requesters.type=1) 
    LEFT JOIN users solvers ON (tu.user_id = solvers.id AND solvers.type=2)

正如您所知,用户表连接两次(作为请求者和具有附加条件的求解器)。使用LEFT JOIN的原因是因为如果没有请求者或没有解算器的记录,INNER JOIN会完全忽略整个记录,直到它有一个请求者和一个求解器。