【发布时间】:2015-06-20 21:39:54
【问题描述】:
好的,所以我对这个数据库的东西很陌生,我正在尝试弄清楚如何同时查询多个表。显然,您可以根据需要查询任意数量的不同表,但如果执行太多连接,可能会遇到性能不佳的情况。但是,我在让 2 个表加入时遇到问题,更不用说 7 个左右的表了,我以后需要加入。
我已经阅读了有关连接表的各种方式的一些信息,并且大多数人似乎更喜欢 union 选项,因为 MySQL 不支持 Full Join。此方法显示的示例不仅让我感到困惑,而且在尝试一次连接 7 个表时看起来会变得非常复杂。然后我看到一篇文章HERE 说MySQL可以使用逗号操作符来模拟全连接。这不仅看起来更容易理解,而且在连接很多表时更容易使用。但我似乎无法让它为我工作,所以希望有人可以帮助我解决这个问题。
编辑 - 这里有更多信息,希望对您有所帮助。
我有两张桌子
test_dogs有品种名称和基本品种信息
lifestyle 作为品种特征,例如狗需要多少运动量、平均健康状况等。
两个表都有一个名为Breed_Name 的列,它是lifestyle 表中的外键。
我想创建一个查询,在这种情况下我可以连接两个表并选择符合以下条件的品种:
Breed_Size = 大
锻炼
我能够连接到我的数据库并对各个表执行查询。
SQL
$large = $db->query('
SELECT *
from test_dogs
where breed_size = "Large"
order by breed_name '); // this query works
$exercise = $db->query('
SELECT *
from lifestyle
where exercise < 7
order by exercise DESC'); // this query works
$join = $db->query('
SELECT test_dogs.*, lifestyle.*
from test_dogs, lifestyle
ON test_dogs.breed_name = lifestyle.breed_name
where test_dogs.breed_size = "Large"
and lifestyle.exercise < 7
order by exercise DESC'); // THIS QUERY DOES NOT WORK
PHP
<h1> Large Breeds </h1> <!--This table works-->
<table>
<tr>
<th>Breed Name</th>
<th>Size</th>
</tr>
<tr>
<?php
while ($rows = $large->fetch()){
echo "<tr><td>" . $rows['Breed_Name'] . "</td><td>" . $rows['Breed_Size'] . "</td></tr>";
};
?>
</table>
<h1> Not High Exercise </h1> <!--This table works-->
<table>
<tr>
<th>Breed Name</th>
<th>Exercise Needs</th>
</tr>
<tr>
<?php
while ($rows = $exercise->fetch()){
echo "<tr><td>" . $rows['Breed_Name'] . "</td><td>" . $rows['Exercise'] . "</td></tr>";
};
?>
</table>
<h1> Large AND Not High Exercise </h1> <!--This table DOES NOT work-->
<table>
<tr>
<th>Breed Name</th>
<th>Size</th>
<th>Exercise Needs</th>
</tr>
<tr>
<?php
while ($rows = $join->fetch()){
echo "<tr><td>" . $rows['test_dogs.Breed_name'] . "</td><td>" . $rows['test_dogs.Breed_Size'] ."</td><td>" . $rows['lifestyle.Exercise'] . "</td></tr>";
};
?>
</table>
我看到有些人如何包含有关他们尝试访问的数据库的信息,但我不知道该怎么做。如果我可以提供更多信息来帮助使这个问题更清楚,请告诉我。
【问题讨论】:
-
请解释您想要的连接结果。目前还不清楚您要达到的目标。
-
联合和连接是两个完全不同的东西。
-
@SamiKuhmonen - 我想这有点不清楚。我试图从每个数据库表中提取某些元素,将结果存储在一个变量中,然后使用该变量在网页上创建一个 php 表。这基本上是学习如何创建搜索引擎的第一步,我的网站访问者可以使用它来搜索我的数据库。
-
您有点混合了隐式(逗号)和显式 JOIN 样式。不。如果事实上,根本不要使用逗号连接。