到目前为止,大量的s/o搜索非常有用。。。下面的方法几乎奏效了。我的问题是,第二个sql查询返回每个“配方”的所有“配料”——而配方1有配料a、c、f,配方2有配料a、g、h。如何限制第二个查询只返回当前循环中配方的成分?我非常感谢php/sql向导的帮助。
具有多对多关系的数据库结构:
RECIPE (recid, title)
REC_ING (recid, ingid)
INGREDIENT (ingid, ingredient)
下面是我的php代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "recipe";
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$xml = new XMLWriter();
$xml->openURI('stackexch.xml');
$xml->setIndent(2);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('recipes');
$recipe = $db->query("SELECT * FROM recipe");
foreach ($recipe as $row) {
$xml->startElement('recipe');
$xml->startElement('title');
$xml->writeRaw($row['title']);
$xml->endElement();
$ingredient = $db->query("SELECT ingredient FROM recipe, rec_ing, ingredient WHERE recipe.recid=rec_ing.recid AND ingredient.ingid=rec_ing.ingid");
foreach ($ingredient as $subrow) {
$xml->startElement('ingredient');
$xml->writeRaw($subrow['ingredient']);
$xml->endElement();
}
$xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
?>
以下是返回的内容:
<?xml version="1.0" encoding="UTF-8"?>
<recipes>
<recipe>
<title>Recipe #1</title>
<ingredient>ingredient A</ingredient>
<ingredient>ingredient C</ingredient>
<ingredient>ingredient F</ingredient>
<ingredient>ingredient G</ingredient>
<ingredient>ingredient H</ingredient>
</recipe>
<recipe>
<title>Recipe #2</title>
<ingredient>ingredient A</ingredient>
<ingredient>ingredient C</ingredient>
<ingredient>ingredient F</ingredient>
<ingredient>ingredient G</ingredient>
<ingredient>ingredient H</ingredient>
</recipe>
</recipes>
3条答案
按热度按时间dnph8jn41#
这将消耗资源:
但是您只使用[title],所以为什么要拉所有列?
对从上面返回的每一行执行此操作:
但您可以在一个查询中同时执行上述两个操作,因此消耗的资源更少:
另外请注意,超过25年前,ansi将一组您应该尝试采用的连接形式化。2个提示:
拒绝在from子句中的表名之间使用逗号,并且
如果一个条件有两个表引用,则该条件属于一个联接,例如recipe.recid=rec\u ing.recid(请参阅?在equals的每一侧都有一个表引用,这是一个连接条件)
最后一个建议:sql查询不必是php代码中的一行。
xe55xuns2#
假设recid是配方的id。试试这个:
因为您已经从配方表中进行了选择,所以无需再次从中进行选择。您可以这样简化代码:
通常,我不建议将变量连接到查询中,但在本例中是安全的,因为您已经从数据库中选择了id。
vddsk6oq3#
欢迎使用stackoverflow。您需要添加
RECIPE.recid='.$row['recid']
在where子句中。不过,从我的Angular 来看,您可以只使用一个查询来简化逻辑。我建议使用内部联接来包含来自多个表的信息。