简体   繁体   English

MySQL:相关表和不相关表之间的区别

[英]MySQL: Difference between relating and not relating tables

I have 2 tables: "catalog" and "press" being "press" the child table and I have them related by id_catalog (pointing to "id" in catalog) inside "press". 我有2个表:“ catalog”和“ press”被“ press”子表,并且它们与“ press”内的id_catalog(指向目录中的“ id”)相关。

I managed to get one field on catalog ("name") and their "press" childs like this for testing porpouses: 我设法在目录(“名称”)上得到一个字段,并像这样用它们的“按”子项来测试海豚:

$query="SELECT catalog.book_title, press.* FROM catalog, press WHERE press.id_catalog = $id";

$book_title = mysql_result($result,$i,"_catalog.book_title");
$media_name = mysql_result($result,$i,"_press.media");
$type = mysql_result($result,$i,"_press.type");
$url = mysql_result($result,$i,"_press.url");

echo $book_title $media_name $type $url;

$book_title = mysql_result($result,$i+1,"catalog.book_title");
$media_name = mysql_result($result,$i+1,"press.media");
$type = mysql_result($result,$i*+1*,"press.type");
$url = mysql_result($result,$i*+1*,"press.url");

echo $book_title $media_name $type $url;

In the query, $id is passed by GET_[] It returns what's expected 在查询中,$ id由GET_ []传递,返回期望的值

Here's the question: What if I don't do the relation in the database? 这里的问题是:如果我不执行数据库中的关系该怎么办? (with the INDEX on id_catalog) Would the query work? (使用id_catalog上的INDEX)该查询有效吗?

I'm answering this 'cause I think if I don't do the relation I could match the fields and make it work anyway... or not? 我正在回答这个问题,因为我想如果我不做这种关系,我可以匹配这些字段并使它正常工作……还是不?

I don't think your issue is with the index (although it would help increase performance). 我认为您的问题不在于索引(尽管这将有助于提高性能)。 I think the issue is this query is producing a Cartesian product -- you aren't relating the 2 tables: 我认为问题在于此查询产生的是笛卡尔积-您没有关联这两个表:

SELECT catalog.book_title, press.* 
FROM catalog, press WHERE press.id_catalog = $id

Instead, it should be something like: 相反,它应该类似于:

SELECT catalog.book_title, press.* 
FROM catalog 
   JOIN press ON catalog.id = press.id_catalog
WHERE press.id_catalog = $id

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

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