简体   繁体   中英

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 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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