简体   繁体   English

将sql查询组合在一起

[英]Combining sql queries together

I am trying to simplify my current query code.我正在尝试简化我当前的查询代码。 Is there a simpler way of combining both queries into one?有没有一种更简单的方法将两个查询合并为一个?

Here is what I have tried so far.这是我迄今为止尝试过的。 Although it seems really messy and clunky.虽然它看起来真的很凌乱和笨重。 This query requests all the clients此查询请求所有客户端

SELECT * FROM clients ORDER BY name DESC

I then have another request inside to find if the client has a booking然后我在里面有另一个请求,以查看客户是否有预订

SELECT * FROM bookings WHERE client_id=$client_id AND done=0

Done represents if the job is completed, and there can only be 1 uncompleted job per client at a time. Done 表示作业是否完成,并且每个客户端一次只能有 1 个未完成的作业。

Explanation:解释:

The code needs to show all the clients and if the client has a booking and if the other database returns a result, the booking button won't appear, if no results (ie, all previous bookings for that client are 1) a book button appears.代码需要显示所有客户,如果客户有预订并且其他数据库返回结果,则不会出现预订按钮,如果没有结果(即该客户之前的所有预订都是 1),则预订按钮出现。

If you just want a flag, then you can use EXISTS :如果你只想要一个标志,那么你可以使用EXISTS

SELECT c.*, 
       (EXISTS (SELECT 1
                FROM bookings b
                WHERE ON c.client_id = b.client_id AND b.done = 0
               )
       ) as has_booking
FROM clients c ;

I think you want:我想你想要:

select c.*, coalesce(b.done, 1) completed
from clients c
left join bookings b on b.client_id = c.client_id and b.done = 0

This attempts to find a uncompleted row in booking for each client.这会尝试为每个客户在booking找到一个未完成的行。 Column completed in the resultset contains 0 if the client has an uncompleted row, else 1 .completed在结果中包含0 ,如果客户有未完成行,否则1

SELECT clients.*, bookings.done
FROM clients
LEFT JOIN bookings ON bookings.client_id = clients.client_id
AND b.done = 0

With the above result, you can add a condition in your view有了上面的结果,你可以在你的视图中添加一个条件

if(done == 0){
     show button code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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