MYSQL Order from another Table

瘦欲@ 提交于 2019-12-05 02:55:51

问题


I have a question.

I have here 2 tables

table 1 : products

product_id , name , images_sideview

table 2 : product_descriptions

product_id , volgnr

I want to sort them with the numbers from Table 2 and volgnr field.

Is there a way to do this with mysql ?


回答1:


There are 2 ways to sort. Ascending order and Descending order. You have not mentioned the order. So I am providing you both answers with 2 variations:

ASCENDING 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 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;

If you want to tell MySQL to first sort FIRST by volgnr and then by product_id:

ASCENDING 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 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;

Hope that helps.

Edit 1:

I have now edited the query so that it does not give you duplicates in results. Try it out and let me know how that goes.

Edit 2: Added Group By clause. Try this out.




回答2:


select *
from products t1
inner join product_descriptions t2 on t1.product_id = t2.product_id
order by t2.volgnr



回答3:


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;


来源:https://stackoverflow.com/questions/9788006/mysql-order-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!