简体   繁体   中英

How to SELECT value from one table based on same value's behavior in another table?

Please help me with this... If I have these tables and columns: TABLE1 with column ID and TABLE2 which has the columns FOO and BAR , both of which contain different id's which all also appear in the ID column of TABLE1 .

I'd like to write a SELECT query to get all id's from ID from TABLE1 but under this condition:

For example, id 101 will be selected from ID if the number ( X ) of rows where id 101 appears under the FOO column of TABLE2 when divided by the number ( Y ) of rows where id 101 appears under the BAR column of TABLE2 , gives a result smaller than a certain value.

So if, say, X / Y < 3 , then id 101 will be selected by the query.

How would such a query look and could it be done in one long query?

Thank you!

You could use a JOIN with subqueries in the FROM clause . The subquery q1 counts the IDs in the foo column that are in both the foo and id columns.

SELECT foo as id FROM (SELECT foo, COUNT(foo) X FROM Table2 WHERE FOO in (SELECT id FROM Table1) GROUP BY foo) q1, (SELECT bar, COUNT(bar) Y FROM Table2 WHERE bar in (SELECT id FROM Table1) GROUP BY bar) q2 WHERE q1.foo=q2.bar and X/Y < 3

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