[英]How do I return a row from one table with the number of matching id's from a second table in MySQL?
[英]MySQL: Return row count from second table using one query
我有以下兩個表。 我需要從lightboxes_tbl中選擇所有燈箱,其中author ='scott@co.com'。 這顯然是最容易的部分。 我被困的地方是我還想在同一個查詢中選擇每個燈箱中的資產數量。 例如,'aircraft-types'燈箱(id = 100 / lightbox_id = 100)將返回2個資產。 '維護'燈箱(id = 101 / lightbox_id = 101)將返回1個資產。
謝謝!
lightboxes_tbl
+-----+----------------+---------------+---------------------+
|id |lightbox_name |author |authoried_viewers |
+-----+----------------+---------------+---------------------+
|100 | aircraft-types |scott@co.com |jon@co.com,aj@co.com |
+-----+----------------+---------------+---------------------+
|101 | maintenance |scott@co.com |nicole@co.com |
+-----+----------------+---------------+---------------------+
lightbox_assets_tbl
+-----+-------------+-------------+---------------+----------+
|id |lightbox_id |asset_name |asset_path | asset_id |
+-----+-------------+-------------+---------------+----------+
|1 |100 |a321.jpg |project1/imgs/ | 3700 |
+-----+-------------+-------------+---------------+----------+
|2 |100 |b757.jpg |project1/imgs/ | 3444 |
+-----+-------------+-------------+---------------+----------+
|3 |101 |engine.jpg |project4/imgs/ | 1444 |
+-----+-------------+-------------+---------------+----------+
利用LEFT JOIN
和COUNT()
SELECT l.*, COUNT(a.lightbox_id) total_assets
FROM lightboxes_tbl l LEFT JOIN lightbox_assets_tbl a
ON l.id = a.lightbox_id
WHERE l.author = 'scott@co.com'
GROUP BY l.id
輸出:
| ID | LIGHTBOX_NAME | AUTHOR | AUTHORIED_VIEWERS | TOTAL_ASSETS | |-----|----------------|--------------|----------------------|--------------| | 100 | aircraft-types | scott@co.com | jon@co.com,aj@co.com | 2 | | 101 | maintenance | scott@co.com | nicole@co.com | 1 |
這是一個SQLFiddle演示
推薦閱讀:
加入assts表:
select
lb.id, lb.lightbox_name, lb.author, lb.authoried_viewers,
sum(a.id is not null) asset_count
from lightboxes_tbl
left join lightbox_asset_tbl a
on a.lightbox_id = lb.id
where author ='scott@co.com'
group by lb.id, lb.lightbox_name, lb.author, lb.authoried_viewers
那里有一個小技巧: sum()
用於計算asst表中有多少行不為空,這對於沒有資產的燈箱會產生總計為零的數字 - 當count()
不會做的時候使用左連接。
順便說一句,在mysql中,如果為true,則布爾結果為1,如果為false則為0,因此將條件求和整齊地計算它的真實次數。
你可能想要這個查詢的內容......
SELECT LBT.id,LBT.lightbox_name,LBT.author,LBTA.id,LBTA.asset_name,LBTA.asset_path,LBTA.asset_id FROM lightboxes_tbl LBT JOIN lightbox_assets_tbl LBTA ON LBTA.lightbox_id = LBT.id WHERE author ='scott @ co。 COM”
azsl1326
這個我寫簡單的查詢,例如,希望它有幫助,
選擇
a.id,a.lightbox_name,b.id,b.lightbox_id,b.asset_name,b.asset_id
來自lightboxes_tbl a
加入lightbox_assets_tbl b
on(a.id = b.lightbox_id)
其中a.author =“scott@co.com”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.