简体   繁体   中英

I need to query 1 table to obtain the total number of rows pertaining to a value in a second and third table

I have 3 Tables:

user_subscriptions

ID  |  SUB_ID  | TYPE |  Type 1 = scripts | Type 2 = packages
 1  |    1     |  1   | 
 2  |    2     |  1   |
 3  |    3     |  1   | 
 4  |    4     |  1   | 
 5  |    1     |  2   |
 6  |    2     |  2   |
 7  |    3     |  2   |
 8  |    4     |  2   | 
 9  |    5     |  1   |
10  |    6     |  2   |
11  |    7     |  1   |
12  |    8     |  1   |
13  |    9     |  2   |

scripts

ID   | AUTHOR_ID |
1    |   58      | 
2    |   58      |
3    |   58      | 
4    |   58      |
5    |   52      |
6    |   53      |
7    |   58      |
8    |   55      | 
9    |   58      |
10   |   56      |

packages

ID   | AUTHOR_ID |
1    |   58      | 
2    |   58      |
3    |   58      | 
4    |   58      |
5    |   56      |
6    |   57      |
7    |   58      |
8    |   58      |
9    |   56      |
10   |   58      |

In the 'user_subscriptions' table, the 'SUB_ID' column corresponds with a script ID or package ID, depending on the type that is set for that subscription.

My goal is to query for the total number of subscriptions to scripts & packages created by a particular author. Author 58 has created 6 Scripts and 7 Packages (total 13) but there are only 9 user subscriptions that are related to author_id 58.

I am having trouble writing a query that will return the user_subscriptions pertaining to author_id 58.

Any and all assistance is greatly appreciated. I am making this query from PHP and will likely use mysqli_num_rows in order to get the count that I need. Thanks again!

SELECT author_id
     , COUNT(*) total
  FROM
     ( SELECT id, author_id FROM scripts
       UNION ALL
       SELECT id, author_id FROM packages
     ) x
 GROUP
    BY author_id;

Note that this solution has fewer words in it than webnoobs comment above ;-)

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