我有一个问题。
我这里有2张桌子
表1:产品
product_id , name , images_sideview
表2:product_descriptions
product_id , volgnr
我想用表2和volgnr字段中的数字对它们进行排序。
有没有办法用mysql做到这一点?
答案 0 :(得分:11)
有两种排序方式。升序和降序。你还没有提到订单。所以我为你提供了两种不同的答案:
提交订单:
SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.product_id ASC, table2.volgnr ASC;
DESCENDING ORDER:
SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.product_id DESC, table2.volgnr DESC;
如果你想告诉MySQL首先按照volgnr排序 FIRST,然后按product_id 排序:
提交订单:
SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.volgnr ASC, table2.product_id ASC;
DESCENDING ORDER:
SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.volgnr DESC, table2.product_id DESC;
希望有所帮助。
修改1:
我现在已经编辑了查询,因此它不会在结果中给出重复项。试一试,让我知道这是怎么回事。
编辑2: 添加了Group By子句。试试这个。
答案 1 :(得分:1)
select *
from products t1
inner join product_descriptions t2 on t1.product_id = t2.product_id
order by t2.volgnr
答案 2 :(得分:0)
SELECT p.'product_id', p.'name', p.'images_sideview'
FROM products p
LEFT JOIN product_descriptions d ON p.product_id = d.product_id
ORDER BY d.volgnr;