我有2张桌子:
Category
主键ID
和列Name
Employee
主键ID
和列Category_id
注意:Category_id
现在正确显示ID
我想为Name
的输出显示ID
而不是Employee
。
尝试:
$categ = mysql_query("SELECT * FROM employee WHERE id = '" . $_GET['id'] . "'");
$rows = array();
while ($row = mysql_fetch_assoc($categ)) {
$website_cat = $row;
}
Category
表:
+----+----------------+
| ID | Name |
+----+----------------+
| 23 | Manager |
| 10 | Boss |
| 14 | Worker |
| 41 | Another |
+----+----------------+
Employee
表:
+----+----------------+
| ID | Category_id |
+----+----------------+
| 1 | Manager |
| 2 | Boss |
| 3 | Worker |
| 4 | Another |
+----+----------------+
输出:
echo $website_cat['category_id'];
答案 0 :(得分:2)
您正在寻找的SQL关键字是JOIN
。您的查询可能是这样的:
SELECT * FROM employee INNER JOIN category ON employee.category_id = category.id WHERE id = ...
或者,更可读:
SELECT
*
FROM
employee
INNER JOIN category
ON employee.category_id = category.id
WHERE
id = ...
(注意:我故意删除了WHERE
子句的最后一位,因为我不习惯将SQL注入漏洞放在答案中。Please read this要正确学习一些正确的基础知识执行涉及用户输入的SQL查询。目前,您的代码对一种非常常见的攻击形式持开放态度。)
由于您的某些列共享相同的名称,您甚至可能希望更明确地请求它们:
SELECT
employee.id AS employee_id,
category.id AS category_id,
category.name AS category_name
FROM
employee
INNER JOIN category
ON employee.category_id = category.id
WHERE
id = ...
然后在您的代码中,您可以访问这些字段:
employee_id, category_id, category_name
所以你可以输出你想要的值:
echo $website_cat['category_name'];
答案 1 :(得分:1)
您需要join类别表
$categ = mysql_query("
SELECT employee.*, category.name as category_name FROM employee
INNER JOIN category on category.id = employee.category_id
WHERE id = '" . $_GET['id'] . "'");
然后使用$website_cat['category_name']