[英]How Can I Query 2 Tables And Multiple Columns?
I researched this a bit already and all my attempts have come up short so far. 我已经对此进行了研究,到目前为止,我的所有尝试都没有完成。 I am trying to perform a mysql query in my php script that deals with multiple tables.
我试图在处理多个表的PHP脚本中执行mysql查询。
Here is what the tables look like: 表格如下所示:
TABLE 1
表格1
name
名称
TABLE 2
表2
Product (name)
产品名称)
Inventory
库存
CatID
猫ID
ProductID
产品编号
TABLE 3
表3
product_url
product_url
"name" (Table 1) must be the sane as "Product" (Table 2). “名称”(表1)必须与“产品”(表2)一样理智。 Next, "Inventory" (table 2) must be = to "Y".
接下来,“库存”(表2)必须为=到“ Y”。 Lastly, "CatID" must be = "2".
最后,“ CatID”必须为=“ 2”。
My attempt looked somewhat like this: 我的尝试看起来像这样:
SELECT 1.name, 2.Product, 2.Inventory, 2.CatID
FROM table1 1, table2 2
WHERE 2.Inventory = 'Y'
AND 1.name = 2.Product
AND 2.CatID = '2'
From the results, I would be looking to get more information from the table such as product description, etc which would be in table1 and table2... I have never joined or queried 2 (or more) tables before. 从结果中,我希望从表中获取更多信息,例如产品描述等,这些信息将在table1和table2中...我之前从未加入或查询过2个(或更多)表。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Try this: 尝试这个:
SELECT table1.Name, table2.Product, tabl2.Inventory, table2.CatID
FROM table1 INNER JOIN table2
ON table1.Name = table2.Product
WHERE table2.CatID = '2'
SELECT t1.name, t2.Product, t2.Inventory, t2.CatID, t2.ProductID
FROM table1 t1
INNER JOIN table2 t2 ON t2.Product = t1.name
WHERE t2.Inventory = 'Y' AND t2.CatID = 2
I'm sorry to say that the database you have to work with was very poorly designed. 很抱歉,您必须使用的数据库设计得很差。 If the query I gave you doesn't work, then make sure you have data in the tables that actually meets the criteria you're looking for.
如果我给您的查询不起作用,请确保表中的数据确实符合您要查找的条件。
Also remember that when you're accessing these fields in PHP, capitalization matters. 还要记住,当您在PHP中访问这些字段时,大小写很重要。 You need to do something like this:
您需要执行以下操作:
<?php
$q = QUERY FROM ABOVE
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)) {
$name = $row["name"];
$product = $row["Product"];
$inventory = $row["Inventory"];
$catid = $row["CatID"];
$productid = $row["ProductID"];
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.