簡體   English   中英

從另一個相關表的計數只有一個的表中選擇

[英]Select from table where count from another related table is only one

我有兩個表都通過 id 相關......我想要使用 eloquent 或 mysql 語句的單個查詢在下面執行......:

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

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

我只希望結果只顯示只有一個請求的客戶

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

如何在 mysql 或 laravel elquent 中制作它????

您可以嘗試以下操作

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

假設你有工作雄辯的模型和關系,你可以這樣做:

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

下一個查詢應該可以解決您的問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM