0

我也想获取类别名称。我有下表

产品表

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

谢谢

4

3 回答 3

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';

对于您提供的数据库结构,可以正常工作

于 2013-10-15T05:56:12.737 回答
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';
于 2013-10-15T06:01:27.143 回答
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;
于 2013-10-15T06:02:47.380 回答