我也希望获取类别名称。我有下表
产品表
mysql> describe prod;
+----------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-----------------+------+-----+---------+----------------+
| pid | int(4) unsigned | NO | PRI | NULL | auto_increment |
| pro_name | varchar(32) | NO | | NULL | |
+----------+-----------------+------+-----+---------+----------------+
类别表
mysql> describe cat;
+----------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-----------------+------+-----+---------+----------------+
| cid | int(4) unsigned | NO | PRI | NULL | auto_increment |
| cat_name | varchar(32) | NO | | NULL | |
+----------+-----------------+------+-----+---------+----------------+
cat_pro
表格[关系表]
mysql> describe cat_pro;
+----------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-----------------+------+-----+---------+----------------+
| cat_id | int(4) unsigned | NO | | NULL | |
| pro_id | int(4) unsigned | NO | | NULL | |
+----------+-----------------+------+-----+---------+----------------+
我的当前 Query
: -
mysql> select pid, pro_name, cat_pro.cat_id
from prod
left join cat_pro on cat_pro.pro_id=prod.pid
where pid='2';
但是当我运行此命令时,它会给我错误说unknown column cat_pro.cat_id in on clause
mysql> select pid, pro_name, cat_pro.cat_id, cat.cat_name
from prod
left join cat_pro on cat_pro.pro_id=prod.pid
left join cat on cat.cid=cat_pro.cat_id
where pid='2'
有什么办法,我可以从cat
表中获取类别名称吗? ,或者我是否必须运行另一个query
来从cat
表格中提取类别名称。
由于
答案 0 :(得分:1)
查询:
select pid, pro_name, cat_pro.cat_id, cat.cat_name
from
prod
inner join
cat_pro
on (cat_pro.pro_id = prod.pid)
inner join
cat
on (cat.cid = cat_pro.cat_id)
where pid='2';
对您提供的数据库结构没有错误
答案 1 :(得分:0)
希望这对你有所帮助。在下面的查询中,我们使用子查询来获取基于category_id的类别名称。
select
prod.pid,
prod.pro_name,
cat_pro.cat_id,
(
select
cat_name
from
Category c
where
c.cid = cat_pro.cat_id
) as category_name
from
prod left join
cat_pro on cat_pro.pro_id=prod.pid
where prod.pid='2';
答案 2 :(得分:0)
试试这个:
SELECT `pid`, `pro_name`, `c`.`cat_id`
FROM `prod` `p`
LEFT OUTER JOIN `cat_pro` `c` ON `c`.`pro_id` = `p`.`pid`
WHERE `p`.`pid` = 2;