简体   繁体   中英

Select from table where count from another related table is only one

I've tow tables both are related by id ... I want a single query using eloquent or mysql statements to do below ... :

  clients
 -----------
| Id | name |
 -----------
| 1  | name1|
 -----------
| 2  | name2|
 -----------
| 3  | name3|
 -----------

  requests
 ----------------
| Id | client_id |
 ----------------
| 1  | 1         |
 ----------------
| 2  | 1         |
 ----------------
| 3  | 2         |
 ----------------
| 4  | 3         |
 ----------------
| 5  | 3         |
 ----------------

I just want the result to show just clients that has only one request

result
 ----------------
| Id | name      |
 ----------------
| 2  | name2     |
 ----------------

How to make it in mysql or laravel elequent ????

您可以尝试以下操作

DB::table('requests')->groupBy('client_id')->havingRaw('COUNT(*) = 1')->get();

假设你有工作雄辩的模型和关系,你可以这样做:

Client::has('requests', '=', 1)->get();

The next query should resolve your problem:

SELECT 
    clients.Id,
    clients.name
FROM requests
JOIN clients ON clients.Id = requests.client_id
GROUP BY clients.Id, clients.name
HAVING COUNT(*) = 1
;

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