如何通过几个id从多个表中执行选择

时间:2011-11-11 14:21:08

标签: php mysql sql

我有3个看起来像这样的表:

game_table
+---------+------------+------------+----------------------+----------+
| game_id | game_title | sponser_id | game expiration date | prize_id |
+---------+------------+------------+----------------------+----------+
prize_table
+----------+---------------------------+------------+-------------+--------------------+--------------------------------------------+
| prize_id | prize_image_name          | prize_cost | prize_title | remaining_quantity | prize_description                          |
+----------+---------------------------+------------+-------------+--------------------+--------------------------------------------+
sponser_table
+------------+--------------+
| sponser_id | sponser_name |
+------------+--------------+

如何构建查询,从3个表中选择所有数据 肉这句话就像伪代码一样:

select all data from game_table and prize_table and sponser_table where   game_table.sponser_id = 2 and game_table.prize_id = 2 
我试过这样的事情:

SELECT game_list.*, prize_list.* ,sponser_list.* FROM game_list, prize_list,sponser_list
WHERE game_list.sponser_id=2  And  game_list.prize_id = 2 And game_list.game_id=2 ; 

但它没有给我带来好结果。

4 个答案:

答案 0 :(得分:1)

您有一个WHERE子句来限制正确的ID,但您没有连接条件来关联您的表。您尝试使用隐式连接语法(以逗号分隔的表格列表),而不是使用明确的JOIN来表示相关列:

SELECT
  game_list.*, 
  prize_list.* ,
  sponser_list.* 
FROM 
  game_list
  JOIN prize_list ON game_list.prize_id = prize_list.prize_id
  JOIN sponser_list ON game_list.sponser_id = sponser_list.sponser_id
WHERE game_list.sponser_id=2  And  game_list.prize_id = 2 And game_list.game_id=2 ;

我建议不要选择每个表中的所有列,因为您要在至少两个位置复制id列。相反,要明确您想要的列。如果您稍后向这些表中添加了不应包含在此查询中的其他列,这也将对您有所帮助。

SELECT
  game_id,
  game_title,
  game_list.sponser_id,
  game_expiration_date,
  game_list.prize_id,
  prize_image_name,
  prize_cost,
  prize_title,
  remaining_quantity,
  prize_description,
  sponser_name    
FROM 
  game_list
  JOIN prize_list ON game_list.prize_id = prize_list.prize_id
  JOIN sponser_list ON game_list.sponser_id = sponser_list.sponser_id
WHERE game_list.sponser_id=2  And  game_list.prize_id = 2 And game_list.game_id=2 ;

答案 1 :(得分:1)

SELECT *
FROM game_table
JOIN prize_table USING (prize_id)
JOIN sponser_table USING (sponser_id)
WHERE sponser_id = 2
AND prize_id = 2
AND game_id = 2

答案 2 :(得分:0)

SELECT 
  game_list.*, prize_list.* ,sponser_list.* 
FROM game_list
JOIN prize_list ON game_list.prize_id = prize_list.prize_id
JOIN sponser_list ON game_list.sponser_id = sponser_list.sponser_id
WHERE 
  game_list.sponser_id=2  And  game_list.prize_id = 2 And game_list.game_id=2 ; 

答案 3 :(得分:0)

根据您的描述,表格似乎是相关的。如果是,则需要使用联接,如下所示:

SELECT *
FROM game_table g
LEFT OUTER JOIN prize_table p ON p.prize_id=g.prize_id
LEFT OUTER JOIN sponser_table s ON s.sponser_id=g.sponser_id
WHERE g.game_id=2