简体   繁体   English

关联数据库中不同表的两个元素

[英]Associate two elements of different tables in the db

I don't know how much to explain this, so I'll give my situation and so you can understand me better. 我不知道要解释多少,所以我会给出我的情况,这样您就可以更好地理解我。

I have a games webpage. 我有一个游戏网页。 In my db, I have two tables: one with my games (with colums like id, name, description, category (this is a number, not a string) , etc.), and another with my categories (with the id and the name). 在我的数据库中,我有两个表:一个带有我的游戏(带有ID,名称,描述, 类别 (这是一个数字,不是字符串)之类的列等),另一个带有我的类别(带有ID和名称)。
When I upload games, instead of assigning into the category column the name of the category, I assign a number, the one which corresponds in the categories table (I do it with a select option like this: 上传游戏时,我没有分配类别名称到类别列,而是分配了一个数字,该数字与类别表中的数字相对应(我使用如下选择选项来完成此操作:

<option value="'.$row['id'].'">'.$row['name'].'</option>

(This is inside a select tag (inside a form) and with a foreach statement so it shows me all the options). (这在select标记内(在表单内),并带有foreach语句,因此它向我显示了所有选项。

So now, what I want is that when I catch the games from the db with a 'SELECT * FROM games', if I call the category element, instead of getting the id of the category, to assign the id with the category name... I don't know how much to explain it but I hope you can understand me. 所以现在,我想要的是,当我使用“ SELECT * FROM games”从数据库中捕获游戏时,如果我调用category元素,而不是获取类别的ID,则为ID分配类别名称。 ..我不知道要解释多少,但我希望你能理解我。

So, what should I use? 那么,我应该使用什么呢?

You can use a LEFT JOIN to pull the category name. 您可以使用LEFT JOIN拉类别名称。 Example: 例:

SELECT 
  g.id g_id,
  g.name g_name,
  g.desc g_desc,
  c.name c_name
FROM games g
LEFT JOIN
  categories c
    ON c.id = g.category

This is an example, you'll need to select the proper columns and assign a unique alias. 这是一个示例,您需要选择适当的列并分配唯一的别名。

I think you want to join the tables so you can get the categoryname from the same query. 我认为您想加入表,以便可以从同一查询中获取类别名称。

You can do it like this: 您可以这样做:

$result = mysql_query("SELECT * FROM games, category WHERE games.category = categoyry.id) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
    echo $row['games.name'].' '.$row['category.name'];
}

you can use just "INNER JOIN or JOIN" to get the result from two tables by just joining them. 您可以只使用“ INNER JOIN或JOIN”将两个表连接起来,从而获得结果。

`SELECT g.*,c.*
 FROM games g
 INNER JOIN categories c on c.categoryid = g.categoryid;`

this will give you just those which are associated categories. 这将只为您提供相关类别。 but if you use "Left Join" it would give you everything from games( http://www.sitepoint.com/understanding-sql-joins-mysql-database/ ) 但是,如果您使用“ Left Join”,它将为您提供游戏的所有内容( http://www.sitepoint.com/understanding-sql-joins-mysql-database/

`SELECT g.*,c.*
 FROM games g
 LEFT JOIN categories c on c.categoryid = g.categoryid;`

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM