仅当同一 order_reference 下文件的所有 print_item_qty 值都等于 5 时,我才尝试构建一个查询,该查询将包含下面数据示例中给定的 order_reference 覆盖文件。
这是否可以使用联接来实现,或者这超出了单个查询的范围?
我尝试过构建内部联接,但无法弄清楚如何限制结果,以便当订单的所有组成部分在 print_item_qty 列中具有相同值时,我只能得到覆盖行。
以下是基本 SELECT 查询和示例数据:
SELECT c1.`order_id`,c1.name1,c1.name2,c1.`print_item_qty`,c1.`sub_item_type`,
c1.`order_reference` FROM print_items;
+--------------+-------+---------+----------------+---------------+-----------------+
| order_id | name1 | name2 | print_item_qty | sub_item_type | order_reference |
+--------------+-------+---------+----------------+---------------+-----------------+
| 000003201875 | Jason | Bramley | 5 | cover | 1875 |
| 000003201875 | Jason | Bramley | 5 | inner | 1875 |
| 000003201875 | Jason | Bramley | 1 | card | 1875 |
| 000003201876 | Jason | Bramley | 5 | cover | 1876 |
| 000003201876 | Jason | Bramley | 5 | inner | 1876 |
+--------------+-------+---------+----------------+---------------+-----------------+
对于上述示例数据,我想要的结果只是下面一行:
+--------------+-------+---------+----------------+---------------+-----------------+
| order_id | name1 | name2 | print_item_qty | sub_item_type | order_reference |
+--------------+-------+---------+----------------+---------------+-----------------+
| 000003201876 | Jason | Bramley | 5 | cover | 1876 |
+--------------+-------+---------+----------------+---------------+-----------------+
如果任何人能够为我指明正确的方向,我将不胜感激。
非常感谢。
最佳答案
因此,您想要验证是否只为该 order_reference 中所有 sub_item_type 的 print_item_qty = 5 的订单选择数据。
为此,请使用子查询,例如
SELECT order_reference,
MAX(print_item_qty),
MIN(print_item_qty)
FROM print_items
GROUP BY order_reference
HAVING MAX(print_item_qty) = 5
AND MIN(print_item_qty) = 5
并加入您的原始数据集。子查询将限制为您想要的 id,并且连接回来将返回与 order_references 关联的所有行,其中每个 sub_item_type 的 print_item_qty = 5,例如
SELECT c1.`order_id`,
c1.name1,
c1.name2,
c1.`print_item_qty`,
c1.`sub_item_type`,
c1.`order_reference`
FROM print_items AS c1
INNER JOIN (SELECT order_reference, MAX(print_item_qty), MIN(print_item_qty) FROM print_items
GROUP BY order_reference HAVING MAX(print_item_qty) = 5 AND MIN(print_item_qty) = 5) AS b
ON c1.order_reference = b.order_reference
关于mysql - 在 MySQL 中使用内连接可以实现这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24311852/