简体   繁体   English

SQL Query根据表中的2条记录从1个表中获取记录

[英]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. 我必须编写一个查询,它将显示特定类型的前25个game_id。 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. 在这里,您可以看到记录1和2对于is_primary = 0和1都具有相同的game_id。我要做的是执行同时具有genre_id和我的查询,并且我必须获取同时属于两者的game_id。 Means game_id which have 6000 as genre_id and is_primary=0 and 6007 as genre_id with is_primary=1. 表示game_id,其中genre_id为6000,is_primary = 0,6007为genre_id,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 . 但是,当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 : JOIN比子查询执行得更好

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 优化 SQL 查询 - 从第二个表中具有多行的两个表中获取记录 - Optimize SQL Query - Fetch records from two tables with multiple rows in second table Sql查询从按单列分组的多条记录中获取单条记录 - Sql query to fetch a single record from a multiple records grouped by a single column 在一个查询中从两个表中选择一个记录,并从另一个表中选择多个记录 - Selecting one record from two tables and multiple records from another table in ONE query 根据最后一条记录获取多条记录更新查询更新表 - fetch multiple records update query update table according to last record oracle查询以从表中获取最后4条记录 - oracle query to fetch the last 4 records from the table SQL查询从一个表获取所有记录,除特定记录,按日期,从另一个表 - SQL Query To Get All Records From One Table, Except A Specific Record, By Date, From Another Table MySQL查询可根据另一个表中的记录将记录插入表中 - MySQL query to insert record into table based on records in another table SQL 查询在一个表中搜索记录并将其替换为另一个表中的多条记录 - SQL query to search for a record in one table and replace it with multiple records from another table sql查询从5个表中获取数据 - sql query to fetch data from 5 tables 从一个表中获取记录,而另一个表中没有记录 - Fetch records from one table where there's not a record in another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM