从多个表中对MYSQL结果进行排序的方法是什么?
我有两张桌子。第一个:
" store_products"表:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Product 1 |
| 2 | Product 2 |
| 3 | Product 3 |
+----+-----------+
这里我放置了产品名称。其他表格包含不同产品型号的价格:
" store_products_variants"表:
+-----+------------+-------------+-------------+
| id | product_id | price_sale | ordering |
+-----+------------+-------------+-------------+
| 5 | 1 | 06.00 | 2 |
| 6 | 1 | 32.00 | 3 |
| 11 | 1 | 56.00 | 1 |
| 14 | 2 | 09.00 | 1 |
| 44 | 3 | 15.00 | 1 |
+-----+------------+-------------+-------------+
我需要创建一个价格(最低和最高)的排序,它只使用第一个变量 - 按列排序"排序"来自" store_products_variants"表
从上面的例子中,结果应该是:
+---+------------+---------------+
| 1 | Product 2 | (price 09.00) |
| 3 | Product 3 | (price 15.00) |
| 2 | Product 1 | (price 56.00) |
+---+------------+---------------+
这在MySQL中是否可行?
答案 0 :(得分:2)
使用ordering
列将正确的变体加入到产品中。
如果正确的ordering
值始终为1,那么这将是查询。
SELECT
products.name,
variants.price_sale
FROM store_products AS products
INNER JOIN store_products_variants AS variants
ON variants.product_id = products.id
AND variants.ordering = 1
ORDER BY variants.price_sale ASC
此查询将首先查找产品的最低ordering
值。然后用它来加入你的结果价格:
SELECT
products.name,
variants.price_sale
FROM
store_products AS products
INNER JOIN (
SELECT
product_id,
MIN(ordering) AS ordering
FROM
store_products_variants
GROUP BY
product_id
) AS variantOrdering
ON variantOrdering.product_id = products.id
INNER JOIN store_products_variants AS variants
ON variants.product_id = variantOrdering.product_id
AND variants.ordering = variantOrdering.ordering
ORDER BY
variants.price_sale ASC
答案 1 :(得分:1)
select t.* from(
select t1.[id], t1.[name],
'(price ' + cast(max(t2.[price_sale]) as varchar(50)) + ')' as [price]
from [#store_products] t1
left join [#store_products_variants] t2
on t1.[id] = t2.[]product_id
group by t1.[id], t1.[name]
)t
Order by len(t.[price]), t.[price];
答案 2 :(得分:0)
是的,这是可能的。尝试使用JOIN命令,并在每个表的ID上加入。
答案 3 :(得分:0)
您好,请使用此查询
Cursor.Position
我认为它会给你想要的结果