1)我有查询来检索文件的ID,如下所示:
SELECT virtuemart_media_id
FROM __virtuemart_product_medias
WHERE virtuemart_product_id = "1"
ORDER by ordering ASC
这给了我一些想法,比如23,7,8,24,那很好。
然后我需要在另一个WHERE语句中使用上面的值来选择那些文件。所以我有这样的事情:
SELECT file_url, virtuemart_media_id
FROM __virtuemart_medias
WHERE virtuemart_media_id IN (
SELECT virtuemart_media_id
FROM __virtuemart_product_medias
WHERE virtuemart_product_id = "1"
ORDER by ordering ASC
)
这也有效,除了我得到的订单文件的结果:7,8,23,24 - 所以不是按顺序23,7,8,24。
问题出在哪里?似乎没有保留内部SELECT的顺序。
答案 0 :(得分:0)
这将取代您的两个查询。
SELECT __virtuemart_medias.file_url, __virtuemart_medias.virtuemart_media_id
FROM __virtuemart_medias INNER JOIN __virtuemart_product_medias ON
__virtuemart_medias.virtuemart_media_id=__virtuemart_product_medias.virtuemart_media_id WHERE
__virtuemart_product_medias.virtuemart_product_id = '1' ORDER BY
__virtuemart_product_medias.ordering ASC
答案 1 :(得分:0)
SELECT a.file_url, a.virtuemart_media_id
FROM __virtuemart_medias a
INNER JOIN __virtuemart_product_medias b ON a.virtuemart_media_id = b.virtuemart_media_id
ORDER BY b.ordering ASC;
这将有效
答案 2 :(得分:0)
IN子句中没有顺序。它只是一组价值观。 (1,2,3)中的x与(3,2,1)中的x相同,(1,2,3)中的x与(3,2,1)中的相同。加入表格即可访问您的订购栏:
SELECT vm.file_url, vm.virtuemart_media_id
FROM __virtuemart_medias vm
INNER JOIN __virtuemart_product_medias vpm
ON vm.virtuemart_media_id = vpm.virtuemart_media_id
WHERE vpm.virtuemart_product_id = 1
ORDER BY vpm.ordering ASC;
答案 3 :(得分:0)
in
的子查询可能会产生多个结果。在这种情况下,您必须定义订购所需的那个。
当替换in
后跟带有join
的子查询时,您需要确保不会意外地乘以记录数。这需要使用聚合或distinct
删除重复项:
SELECT m.file_url, m.virtuemart_media_id
FROM __virtuemart_medias join
(select virtuemart_media_id, min(ordering) as ordering
from __virtuemart_product_medias
where WHERE virtuemart_product_id = 1
group by virtuemart_media_id
) mi
on m.virtuemart_media_id = mi.virtuemart_media_id
ORDER by mi.ordering ASC;