SQL:将2个选择查询的结果连接成1行

时间:2014-02-28 14:26:42

标签: mysql sql join union

如果两个表中都有数据

,我有这个查询
SELECT a.location, b.location, a.refno, b.note
FROM (
    SELECT location, refno
    FROM tableA WHERE refno = '1234'
) a, (
    SELECT location, note FROM tableB WHERE note = LN1234567
) b

但有些时候,任何一个表中都没有数据用于WHERE子句中的特定匹配

我也试过这个可以工作,但我需要一行数据

SELECT location, refno
FROM tableA
WHERE refno = '1234'

UNION

SELECT location, note
FROM tableB
WHERE note = 'LN1234567'

我的问题是,是否有另一种查询两个表的方法,所以我从一个或两个表中得到一行数据?

2 个答案:

答案 0 :(得分:3)

您可以尝试:

SELECT MAX(location_a) AS location_a,
       MAX(refno_a) AS refno_a,
       MAX(location_b) AS location_b,
       MAX(refno_b) AS refno_b
FROM (
SELECT location AS location_a,
       refno AS refno_a,
       NULL AS location_b,
       NULL AS refno_b
FROM tableA
WHERE refno = '1234'
UNION ALL
SELECT NULL AS location_a,
       NULL AS refno_a,
       location AS location_b,
       location AS refno_b
FROM tableB
WHERE note = 'LN1234567') s

答案 1 :(得分:2)

假设您希望双方都有匹配的位置,则需要left join。这是一个简化版本:

SELECT a.location, b.location, a.refno, b.note
FROM tableA a LEFT JOIN
     tableB b
     on a.location = b.location
WHERE a.refno = '1234' and b.note = 'LN1234567';

如果您确实需要cross join(同一行中的不同位置)但仍想要结果,我认为您需要union all

SELECT a.location, b.location, a.refno, b.note
FROM tableA a CROSS JOIN
     tableB b
WHERE a.refno = '1234' and b.note = 'LN1234567'
UNION ALL
SELECT a.location, NULL, a.refno, NULL
FROM tableA
WHERE NOT EXISTS (SELECT 1 FROM tableB b WHERE b.note = 'LN1234567');