无结果的子查询

ar7v8xwq  于 2021-07-26  发布在  Java
关注(0)|答案(5)|浏览(272)

我有两个问题,我想合并成一个。
查询1: SELECT Quantity FROM Table1 WHERE IdProduct = 1234 问题2: SELECT Supplier FROM Table2 WHERE IdProduct = 1234 以下是我所做的:

SELECT
   bloc1.Quantity AS qty,
   bloc2.Supplier AS supplier
FROM    
   (SELECT Quantity FROM Table1 WHERE IdProduct = 1234) bloc1,
   (SELECT Supplier FROM Table2 WHERE IdProduct = 1234) bloc2

大多数时候一切都很顺利,但不幸的是,有时两个查询中的一个没有返回结果。。。在这种特定情况下,两个查询“fail”。

flvlnr44

flvlnr441#

你的代码正在执行 CROSS JOIN 两个查询的结果。
因此,如果其中任何一个没有返回行,则结果是没有行。
如果您确定这两个查询只返回一行,请将它们的结果用作列:

SELECT 
  (SELECT Quantity FROM Table1 WHERE IdProduct = 1234) qty,
  (SELECT Supplier FROM Table2 WHERE IdProduct = 1234) supplier
wnvonmuf

wnvonmuf2#

对我来说,像这样把这些问题拼凑在一起是很了不起的。但是,如果您想让它在其中一个表中缺少记录的情况下生存,则需要一个 OUTER JOIN 某种程度上。看到了吗https://dev.mysql.com/doc/refman/5.7/en/join.html.

wgxvkvu9

wgxvkvu93#

你可能想要一个“完全的外部连接”。不幸的是,mysql没有实现完全的外部连接(为什么在这个时代?)。
无论如何,您可以使用解决方法来模拟它:

SELECT
   bloc1.Quantity AS qty,
   bloc2.Supplier AS supplier
FROM (SELECT Quantity FROM Table1 WHERE IdProduct = 1234) bloc1
LEFT JOIN (SELECT Supplier FROM Table2 WHERE IdProduct = 1234) bloc2 on 1 = 1
UNION
SELECT
   bloc1.Quantity AS qty,
   bloc2.Supplier AS supplier
FROM (SELECT Quantity FROM Table1 WHERE IdProduct = 1234) bloc1
RIGHT JOIN (SELECT Supplier FROM Table2 WHERE IdProduct = 1234) bloc2 on 1 = 1

在mysql 8.x中,您可以通过使用ctes删除冗余(并稍微缩短它)。例如:

with
bloc1 as (SELECT Quantity FROM Table1 WHERE IdProduct = 1234),
bloc2 as (SELECT Supplier FROM Table2 WHERE IdProduct = 1234)
SELECT
   bloc1.Quantity AS qty,
   bloc2.Supplier AS supplier
FROM bloc1 LEFT JOIN bloc2 on 1 = 1
UNION
SELECT
   bloc1.Quantity AS qty,
   bloc2.Supplier AS supplier
FROM bloc1 RIGHT JOIN bloc2 on 1 = 1
pgpifvop

pgpifvop4#

你可以试试下面的-

select 
(SELECT Quantity FROM Table1 WHERE IdProduct = 1234) as qty,
(SELECT Supplier FROM Table2 WHERE IdProduct = 1234) as supplier
8dtrkrch

8dtrkrch5#

你可以连接两个表table1和table2你可以做:

SELECT qty,sup
    FROM   (SELECT Quantity as qty,supplier as sup
        FROM Table1 
        INNER JOIN Table2
        ON table1.IdProduct=table2.IdProduct AND IdProduct=1234);

你可以查看这个来获得更多关于mysql中连接的信息https://www.mysqltutorial.org/mysql-join/

相关问题