[英]Combining 2 sql queries into one
I spent many hours combining my query into one. 我花了很多时间将查询合并为一个查询。 I have 3 database table.
我有3个数据库表。 This is example schema.
这是示例架构。
I have only user name from session. 我只有会话用户名。 I need take all tickets from database from user company.
我需要从用户公司的数据库中获取所有票证。
Example: 例:
User A working in company B. 用户A在公司B中工作。
Company B have many workers. B公司有很多工人。 Workers creating tickets.
制作票的工人。
User A after login see all tickets from yours company. 登录后的用户A查看您公司的所有票证。
I now done this using 2 query: 我现在使用2个查询完成此操作:
- Take usera A company id -以用户名A公司ID
- Take tickets where users work in specifist company. -在用户在特定公司工作的地方拿票。
This should do it: 应该这样做:
SELECT *
FROM User u1
INNER JOIN User u2 on u2.id_company = u1.id_company
INNER JOIN Ticket t on t.id_author = u2.id_user
WHERE u1.Name = @SessionUser
Is this what you are looking for? 这是你想要的?
select t.*
from users u join
tickets t
on u.id_user = t.id_author
where u.company_id = (select u2.company_id from users u2 where u2.id_user = 'UserA');
Joins are typically faster than subqueries, however a lot of DBMS' optimize subqueries into joins, so the difference between the queries is probably not important. 联接通常比子查询快,但是许多DBMS将优化子查询变为联接,因此查询之间的区别可能并不重要。 Below is a reworked version of Gordon Linoff's query removing the subquery.
下面是Gordon Linoff的查询的重做版本,其中删除了子查询。
select t.* from Users u1
join User u2 on u2.id_company = u1.id_company
join Ticket t on t.id_author = u1.id_user
where u1.id.user = 'User1';
However again, if your database optimizes the SQL the difference is negligible. 但是同样,如果您的数据库优化了SQL,则差异可以忽略不计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.