我对相关产品有一个简单的设置。我的数据库有两个表:
product
表和id, name
列和联结表product_assignments
和product_id, related_id, order
列。
我需要获取所有相关产品,并按order
列进行排序
SELECT * FROM `products` LEFT JOIN
`related_assignments` `ra` ON `products`.`id` =
`ra`.`product_id` WHERE `id` IN (412, 1663, 1928) ORDER BY
`ra`.`order` DESC
我没有看到任何错误,我得到了所有三个记录(412、1663和1928年),但是是按其ID而不是按顺序字段排序的。
如何用一个SQL请求对它们进行排序?
产品
+------+-------+
| id | name |
+------+-------+
| 412 | Watch |
| 1663 | Book |
| 1928 | Phone |
| 2000 | Cup |
+------+-------+
相关
+------------+------------+-------+
| product_id | related_id | order |
+------------+------------+-------+
| 2000 | 412 | 1 |
| 2000 | 1663 | 2 |
| 2000 | 1928 | 0 |
+------------+------------+-------+
答案 0 :(得分:3)
根据示例数据和预期结果,您似乎需要使用ra.related_id
作为连接条件,而不是ra.product_id
,
在Left join
上使用products.id =ra.product_id
时,它仅返回id = 2000
行数据。但是您的where子句使用id IN (412, 1663, 1928)
,这将使ra.order
都为null
,这样order by ra.order
将一无所有。
create table products(
id int,
name varchar(50)
);
insert into products values ( 412, 'Watch');
insert into products values (1663, 'Book ');
insert into products values (1928, 'Phone');
insert into products values (2000, 'Cup ');
create table Related(
product_id int,
related_id int,
`order` int
);
insert into Related values (2000, 412 ,1 );
insert into Related values (2000, 1663 ,2 );
insert into Related values (2000, 1928 ,0 );
查询1 :
SELECT *
FROM `products` LEFT JOIN
`Related` `ra` ON `products`.`id` =
`ra`.`related_id`
WHERE `id` IN (412, 1663, 1928)
ORDER BY `ra`.`order` DESC
Results :
| id | name | product_id | related_id | order |
|------|-------|------------|------------|-------|
| 1663 | Book | 2000 | 1663 | 2 |
| 412 | Watch | 2000 | 412 | 1 |
| 1928 | Phone | 2000 | 1928 | 0 |