sql order by via连接表

djmepvbi  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我有一个简单的设置相关产品一对多。我的数据库有两个表: product 带的表格 id, name 列和联接表 product_assignmentsproduct_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

我看不到任何错误,我得到所有三个记录(41216631928),但按其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 |
+------------+------------+-------+
gojuced7

gojuced71#

从您的示例数据和预期结果来看,您似乎需要使用 ra.related_id 是连接条件而不是 ra.product_id ,
当你使用 Left joinproducts.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

结果:

|   id |  name | product_id | related_id | order |
|------|-------|------------|------------|-------|
| 1663 | Book  |       2000 |       1663 |     2 |
|  412 | Watch |       2000 |        412 |     1 |
| 1928 | Phone |       2000 |       1928 |     0 |

相关问题