我正在使用sql查询中的一个问题 这是我的问题: -
$query = 'SELECT
products.id, products.ProductName, products.smallimage as proSmallImage
FROM
products
LEFT JOIN
productscolors
ON
productscolors.proid =products.id
WHERE
products.id!="'.$productId.'"
AND
products.Enable="YES"
AND
products.undercatid in("22","16")
GROUP BY
productscolors.proid
ORDER BY
rand() limit 0,6';
这个查询对我来说很好,但我面临的一个问题是
您在查询中看到了这一点
products.undercatid in("22","16") group by productscolors.proid order by rand() limit 0,6
这将返回22和16中undercatid的随机数据 但我想要来自22个id的3个记录和来自16个id的3个记录 我当前的查询提供来自两个查询的随机数据,即(有时它从22个undercatid中获得5个,从16个undercatid中获得1个等) 任何人都可以帮我解决这个问题。 我想要来自undercatid
的3-3条记录答案 0 :(得分:1)
你可以使用单一选择的联合
select * from (
SELECT products.id, products.ProductName, products.smallimage as
proSmallImage FROM products LEFT JOIN productscolors ON
productscolors.proid =products.id where products.id!="'.$productId.'" and
products.Enable="YES" and products.undercatid = "22"
group by productscolors.proid order by rand()
limit 0,3
) t1
union all
select * from (
SELECT products.id, products.ProductName, products.smallimage as
proSmallImage FROM products LEFT JOIN productscolors ON
productscolors.proid =products.id where products.id!="'.$productId.'" and
products.Enable="YES" and products.undercatid = "16"
group by productscolors.proid order by rand()
limit 0,3
) t2
答案 1 :(得分:0)
SELECT products.id, products.ProductName, products.smallimage as proSmallImage FROM products where products.undercatid in("22") limit 0,3
UNION ALL
SELECT products.id, products.ProductName, products.smallimage as proSmallImage FROM products where products.undercatid in("16") limit 0,3
LEFT JOIN productscolors ON productscolors.proid =products.id
where products.id!="'.$productId.'" and products.Enable="YES"
group by productscolors.proid
order by rand()