0

我有以下表格:

   Products:

+---------------------------+
|id|name |details  |price|cn|
|__|_____|_________|_____|__|
| 1|pen  |somethi  |100  |10|
| 2|paper|something|30   |11|
+---------------------------+

Categories:

+----------------------------+
|id | name      |parent_id   |
|____________________________|
|1  | granny    | 0          |
|2  | dad       | 1          |
|3  | grandson  | 2          |
|4  | grandson 2|  2         |
+----------------------------+

Products2categories:

+-------------------------------+
| id  | product_id | category_id|
|_______________________________|
| 1   | 1          | 3          |
| 2   | 1          | 2          |
| 3   | 1          | 1          |
+-------------------------------+

我想做一个查询,该查询将返回与某些产品相关的所有类别。

例如:当我提供产品 ID 时,1我想得到结果 grandson,dad,granny(与此产品相关的类别名称)

这是我的尝试:

SELECT `categories`.`name`
FROM `categories` 
JOIN (
    SELECT `products2categories`.`category_id`,`products2categories`.`product_id`
    FROM `products2categories` a
        JOIN `products`
        ON `products`.`id` = `products2categories`.`product_id`
)

ON `categories`.`id` = `products2categories`.`category_id`

我有以下错误:

Every derived table must have its own alias

我想在这里得到一些帮助:)

提前致谢!

4

2 回答 2

0

除非我误解了你的说法,否则我相信你把事情复杂化了。根据您对所需内容的口头描述(并忽略您的代码),这将满足您的要求:

SELECT name FROM categories WHERE id IN (SELECT id FROM products2categories WHERE product_id = 1);

编辑:这是一个完整的测试

CREATE TABLE `categories` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `categories` VALUES (1,'granny',0),(2,'dad',1),(3,'grandson',2),(4,'grandson 2',2);

CREATE TABLE `products` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `details` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `cn` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `products` VALUES (1,'pen','somethi',100,10),(2,'paper','something',30,11);

CREATE TABLE `products2categories` (
  `id` int(11) DEFAULT NULL,
  `product_id` int(11) DEFAULT NULL,
  `category_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `products2categories` VALUES (1,1,3),(2,1,2),(3,1,1);

mysql> SELECT name FROM categories WHERE id IN (SELECT id FROM products2categories WHERE product_id = 1);
+----------+
| name     |
+----------+
| granny   |
| dad      |
| grandson |
+----------+
3 rows in set (0.00 sec)
于 2013-08-13T20:14:16.423 回答
-1

好吧,我刚刚发现我做的太难了,实际上是这样。

对于将来某个时候会遇到它的人,这里是解决方案:

SELECT `categories`.`name`
FROM `categories` 
JOIN `products2categories`
ON `categories`.`id` = `products2categories`.`category_id`
WHERE `products2categories`.`product_id` = 1
于 2013-08-13T20:26:38.007 回答