我有3個表格:門票,tickets_users和用戶。我的問題是,在用戶表中我有2種類型的用戶:請求者和求解器:類型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
謝謝,
在此期間,我想我找到了參加子句中使用子查詢的解決方案,但對我來說,它看起來簡陋:
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
加入表格兩次 - 或者玩弄MAX(CASE WHEN ... THEN ... END) – Strawberry