简体   繁体   中英

SQL Query to fetch record from 1 tables based on 2 records in the table

I have to write a query which will display the top 25 game_id which are under specific genre. Database table is like

| id | genre_id | game_id | is_primary |
----------------------------------------
  1    6000       12345      0
  2    6007       12345      1
  3    6000       23492      0
  4    6007       82837      1
----------------------------------------

Here you can see that record 1 and 2 have same game_id for both is_primary = 0 and 1. What i have to do is to execute a query having both the genre_id with me and i have to fetch the game_id which falls under both. Means game_id which have 6000 as genre_id and is_primary=0 and 6007 as genre_id with is_primary=1.

Searched on net but no success.

I tried this query

 SELECT game_id FROM table_name WHERE 
(SELECT game_id FROM table_name WHERE genre_id=6000 AND is_primary=0) 
AND ganre_id=6007 AND is_primary=1;

But this query is giving error as Subquery returns more than one value .

Try this query (UPDATED)

SELECT game_id FROM table_name WHERE game_id IN(SELECT game_id FROM table_name WHERE genre_id=6000 AND is_primary=0)
 AND ( ganre_id=6007 AND is_primary=1);

JOIN performs much better than subqueries :

SELECT t1.game_id
FROM table_name t1
JOIN table_name t2 ON (t1.game_id = t2.game_id AND t2.genre_id = 6000 AND t2.is_primary = 0)
WHERE (t1.genre_id = 6007 AND t1.is_primary = 1)

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