我有两张桌子,
agent(id, name, password, ..., shop_id);
shop(id, name, address, ...);
现在我想获取代理商的商店名称,我该怎么办? 我应该使用两个序列sql查询,
<?php
$qstr = <<<SQL
SELECT * FROM agent WHERE id=$id;
SQL;
$result = $conn->query($qstr);
$row = $result->fetch_assoc();
foreach ($row as $key => $value)
$$key = $value;
$qstr = <<<SQL
SELECT name FROM shop WHERE id=$shop_id;
SQL;
$result = $conn->query($qstr);
$row = $result->fetch_assoc();
$shop_name = $row['name'];
?>
或者我应该为此选择创建一个视图,
CREATE VIEW f_agent AS SELECT agent.id AS id ,agent.name AS name, shop.id AS shop_id, shop.name AS shop_name FROM agent, shop WHERE agent.shop_id=shop.id;
或者我应该只使用sql,
SELECT agent.id AS id ,agent.name AS name, shop.id AS shop_id, shop.name AS shop_name FROM agent, shop WHERE agent.shop_id=shop.id and agent.id=$id;
最好的方法是什么?
感谢。
答案 0 :(得分:3)
如果这只是您将在前端页面中使用的特定查询,那么简单的SQL应该最有效。 没有必要为您想要从MySQL获得的每个可能的结果集创建一个视图。
如果我可以提出建议,请考虑SQL92 ANSI语法
SELECT agent.id AS id ,agent.name AS name, shop.id AS shop_id, shop.name AS shop_name
FROM agent
INNER JOIN shop ON agent.shop_id=shop.id
WHERE agent.id=$id;
在没有的情况下,你应该使用循环为这个结果集的查找列从PHP多次访问MySQL。
答案 1 :(得分:1)
我不会使用视图进行这样一个简单的查询,使用两个单独的结果似乎毫无意义所以我建议使用最后一个查询
答案 2 :(得分:0)
我是新手来运行这样的查询,但我觉得这个帖子非常有用。这样的事情也会起作用吗?
$query = "SELECT shop.id, shop.name, agent.name FROM shop LEFT JOIN agent ON shop.id = agent.id";
$res = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($res)){
echo $row['shop']['name']. " - ". $row['agent']['name'];
echo "<br />";
}