我需要帮助将多个 SQL 查询合并为一个...
我有一个用于 orderid 或 sampleref 的搜索框。一个订单中最多可能包含 99 个 sampleref,因此我希望客户能够提取与其订单号关联的所有 sampleref 的列表,无论他们是按 orderid 还是按他们的 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 |
+----+---------+-----------+
谢谢
亨利
答案 0 :(得分:0)
以下将为您提供所需的内容。
select r2.orderid, r2.sampleref
from result r
join result r2 on r.orderid = r2.orderid
where r.sampleref = 'TEST12345' or r.orderid = <orderid>
答案 1 :(得分:0)
您可以将 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 或样本参考。如果给出,第一个条件以相同的顺序返回所有内容。第二个返回与给定示例引用相同顺序的所有内容。