使用第一个SQL select语句会导致第二个select语句的结果



我想要一些帮助,将多个SQL查询组合成一个。。。

我有一个orderid或sampleref的搜索框。一个订单中可能有多达99个sampleref,因此我希望客户能够调出与其订单号相关的所有sampleref的列表,无论他们是按订单ID还是某个sampleref进行搜索。本质上,我想做的是,

SELECT `orderid` as OrderNumber FROM `results` WHERE `sampleref` = 'TEST12345';
SELECT * FROM `results` WHERE `orderid` = OrderNumber GROUP BY `sampleref`;

为了清楚起见,我将其放入Maria DB mysql服务器的PHP脚本中

这是一个示例数据库

+----+---------+-----------+
| id | orderid | sampleref |
+----+---------+-----------+
|  1 |  101388 | TEST12345 |
|  2 |  101388 | TEST54321 |
|  3 |  333444 | ABC123    |
|  4 |  333444 | ABC321    |
+----+---------+-----------+

感谢

Henry

以下内容将提供您想要的内容。

select r2.orderid, r2.sampleref 
from result r 
join result r2 on r.orderid = r2.orderid 
where r.sampleref = 'TEST12345' or r.orderid = <orderid>

您可以将or与相关子查询一起使用:

SELECT r.*
FROM results r
WHERE r.orderid = $orderid OR
EXISTS (SELECT 1
FROM results r2
WHERE r2.orderid = r.orderid AND r2.sampleref = $sampleref
);

注意:这需要两个参数——订单id或样本ref。如果给定了第一个条件,则返回具有相同订单的所有内容。第二个返回与给定样本参考相同顺序的所有内容。

最新更新