我使用查询1检索三个数据集:查找新产品,查询2:销售中的产品,查询3:流行产品,我需要查找产品是否是新的并且在销售中并且是流行的,或者产品是否只是新的或在销售中等。但由于我将查询限制为 5,因此可能无法同时获得相同的 ID。我还添加了 PHP 代码,但正如我所提到的,它在逻辑上是错误的。最好的方法是什么,我需要你的帮助。在此先感谢 Query1:
SELECT p.`ProductID`,`TypeID`,c.CompanyID as CID,c.`Name` as CN,p.`Name`,`Picture`,`Price`,s.`SalePrice`,Count(l.ProductID) as Likes,'1' as popular
FROM `Product` p inner join Company c on c.CompanyID=p.CompanyID inner join Likes l on l.ProductID=p.ProductID left outer join Sale s on s.ProductID=p.ProductID
where l.ts>date_sub(now(), INTERVAL 7 DAY) and c.CompanyID in(1,2,3) group by p.`ProductID`,`TypeID`,c.`Name`,p.`Name`,`Picture`,`Price`
order by Likes desc LIMIT 0,5
查询2:
SELECT p.`ProductID`,`TypeID`,c.CompanyID as CID,c.`Name` as CN,p.`Name`,`Picture`,`Price`,s.`SalePrice`,s.Endtime,s.Begintime,'1' as sale
FROM `Product` p inner join Company c on c.CompanyID=p.CompanyID inner join Sale s on s.ProductID=p.ProductID left outer join SaleSizeLimit sl on sl.SaleID=s.SaleID where now()>=s.Begintime and s.Endtime>=now() and c.CompanyID in(1,2,3)
order by s.Endtime asc LIMIT 0,5
查询3:
SELECT p.`ProductID`,`TypeID`,c.CompanyID as CID,c.`Name` as CN,p.`Name`,`Picture`,s.`SalePrice`,`Price`,'1' as new
FROM `Product` p inner join Company c on c.CompanyID=p.CompanyID left outer join Sale s on s.ProductID=p.ProductID where p.ts>date_sub(now(), INTERVAL 7 DAY) and c.CompanyID in(1,2,3) order by p.`ProductID` desc LIMIT 0,5
PHP代码:
function Discriminate($set1,$set2,$set3) { // popular,sale,new
$drt=array();
$drv=0;
if(count($set1)>0){
$drv=1;
$drt=$set1;
if (count($set2)>0){
foreach ($set2 as $p2) {
$interim=0;
$i=0;
foreach ($set1 as $p1) {
if($p1->ProductID==$p2->ProductID){
$drt[$i]->Sale=1;
$interim=1;
}
$i++;
}
if($interim==0){
$drt[]=$p2;
}
}
}
$seti=$drt;
if (count($set3)>0){
foreach ($set3 as $p3) {
$interim=0;
$i=0;
foreach ($seti as $pi) {
if($pi->ProductID==$p3->ProductID){
$drt[$i]->New=1;
$interim=1;
}
$i++;
}
if($interim==0){
$drt[]=$p3;
}
}
}
}
else{ // there is no new product in this company
if(count($set2)>0){
$drv=1;
$drt=$set2;
if (count($set3)>0){
foreach ($set3 as $p3) {
$interim=0;
$i=0;
foreach ($set2 as $p2) {
if($p2->ProductID==$p3->ProductID){
$drt[$i]->New=1;
$interim=1;
}
$i++;
}
if($interim==0){
$drt[]=$p2;
}
}
}
}
else{ // there is no sale in this company
if(count($set3)>0){
$drv=1;
$drt=$set3;
}
else{ // there is no popular product in this company
$drv=0;
}
}
}
if($drv==1){
return $drt;
}
else{
return 0;
}
} // end discrimination