简体   繁体   中英

Return results of SQL query on one row

SELECT
    Tickets.id,
    (SELECT Users.Name FROM Users INNER JOIN Tickets ON Tickets.Creator = Users.id) AS naam,
    (SELECT Users.Name FROM Users INNER JOIN Tickets ON Tickets.Owner = Users.id) AS name
FROM Tickets
WHERE Tickets.id = 64;

I want on one row

id, username(Tickets.creator= Users.id), username(where Tickets.Owner = Users.id)

Users

id | name
----------
1  | jan
2  | henk
3  | maria

tickets

ticketsid | owner     | creator
-------------------------------
1         | 3         | 2
2         | 1         | 3
3         | 2         | 3

Your queries want to be correlated with the outer query. You as missing that by doing an additional join to tickets :

SELECT
    Tickets.id,
    (SELECT Users.Name FROM Users WHERE Tickets.Creator = Users.id) AS naam,
    (SELECT Users.Name FROM Users WHERE Tickets.Owner = Users.id) AS name
FROM Tickets
WHERE Tickets.id = 64;

You can also express this query with join s:

select t.id, uc.name as CreatorName, uo.name as OwnerName
from Tickets t left outer join
     Users uc 
     on t.Creator = uc.id left outer join
     Users uo
     on t.Owner = uo.id
where t.id = 64;

This would be the more typical way of expressing this query.

How about

select t.id, o.name, c.name
  from tickets t
  join users o on o.id = t.owner
  join users c on c.id = t.creator
 where t.id = 64;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM