开发者

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.

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 c开发者_如何学Combined with a column saying "number of Expansions" that lists the number of expansions for each toy identified to have no owner

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. i.e. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜