简体   繁体   English

来自MYSQL数据库的结果,不是基于一个,而是基于几个表的结果

[英]Results from MYSQL database based, not one, but on results from a few tables

So here I am and need to see some results from a MYSQL database based not on one but on results from a few tables. 因此,在这里,我需要查看不是基于数据库而是基于一些表的结果的MYSQL数据库的一些结果。

TABLE DESCRIPTION: 表说明:

Metaexplanation:

Tablename

Row1,Row2,Row3....Row(N)

Tables:

---------------
|table toy  |
------------------------------ 
|toy_id | name | description  |
------------------------------


--------------------
|table owned_toy  |
----------------------------
| owner  | toy_id          |
----------------------------


--------------------
|table toy_expansions |
-------------------------------
| expansion | toy_id          |
-------------------------------

I created a query to identify toys with no owner assigned 我创建了一个查询来识别未分配所有者的玩具

SELECT DISTINCT * from toy WHERE NOT EXISTS (SELECT * FROM ownedtoy WHERE owned_toy.toy_id = toy.id);

That worked and I was able to identify things that had no owner. 那行得通,我能够确定没有所有者的事物。

Now to make things more interesting I am trying to find out a way to discover how many expansions exist for each of the toys that I have identified in the query above. 现在,为了使事情变得更有趣,我试图找到一种方法来发现我在上面的查询中识别出的每个玩具有多少种扩展。

I can count the total number of expansions to the toys using: 我可以使用以下方法计算玩具的展开总数:

Select COUNT(expansion) from toy_expansions;

However what I need is to see the total number of expansions for each DISTINCT toy that does not yet have an owner, and it needs to be sorted so that I see the results from the first query combined with a column saying "number of Expansions" that lists the number of expansions for each toy identified to have no owner 但是,我需要的是查看每个尚未拥有所有者的DISTINCT玩具的展开总数,并且需要对其进行排序,这样我才能看到第一个查询的结果与一列“展开数目”的组合列出了每个没有所有者的玩具的扩展数量

I would like to be able to adding the results by combining the original query with a statement like this: 我希望能够通过将原始查询与这样的语句结合来添加结果:

Select COUNT(expansion) as "Number of expansions" from toy_expansions

Also just to make it a little more difficult I would like to be able to execute it in one single query without creating extra tables etc. ie without making any changes to the db itself. 同样只是为了使其更加困难,我希望能够在一个查询中执行它而无需创建额外的表等,即无需对数据库本身进行任何更改。

Any ideas ? 有任何想法吗 ?

SELECT t.name, COUNT(te.expansion) AS NumberOfExpansions
    FROM toy t
        LEFT JOIN toy_expansions te
            ON t.id = te.toy_id
        LEFT JOIN owned_toy ot
            ON t.id = ot.toy_id
    WHERE ot.toy_id IS NULL
    GROUP BY t.name

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

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