MySQL:使用一个查询从第二个表返回行计数

时间:2014-12-27 04:18:53

标签: mysql

我有以下两张表。我需要从lightboxes_tbl中选择所有的灯箱,其中author =&sc ;; scott @ co.com'。这显然很容易。我被困的地方是我还想在同一个查询中选择每个灯箱中的资产数量。例如,'飞机类型' lightbox(id = 100 / lightbox_id = 100)将返回2个资产。维护' lightbox(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     |
+-----+-------------+-------------+---------------+----------+

4 个答案:

答案 0 :(得分:2)

利用LEFT JOINCOUNT()

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 演示

推荐阅读:

答案 1 :(得分:1)

加入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表中有多少行不为空,这对于没有资产的灯箱会产生零总数 - {{1使用左连接时不会这样做。

BTW,在mysql中,如果为true,则布尔结果为1,如果为false则为0,因此将条件求和整齐地计算它的真实次数。

答案 2 :(得分: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 =&# 39; scott@co.com'

答案 3 :(得分:0)

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”