苦苦挣扎着编写嵌套查询

时间:2013-08-13 20:08:17

标签: mysql sql

我有以下表格:

   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时,我希望得到结果 孙子,爸爸,奶奶(该产品所属类别的名称)

这是我的尝试:

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

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

提前致谢!

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:-1)

好吧,我刚刚发现我实际上做得太难了。

对于将来会遇到的人,以后就是解决方案:

SELECT `categories`.`name`
FROM `categories` 
JOIN `products2categories`
ON `categories`.`id` = `products2categories`.`category_id`
WHERE `products2categories`.`product_id` = 1
相关问题