UNION两个带别名的查询,WHERE条件别名

时间:2015-11-11 12:55:29

标签: mysql sql

参考下面的查询:

/*select customers with data*/
SELECT tbl2.id,tbl2.customer,count from tbl1
JOIN tbl2 ON tbl2.id = tbl1.id
WHERE tbl2.customer = @customer /*parameter*/

UNION

/*select all customers*/
select id,costumer,NULL as 'count' from tbl1  

以上查询将输出:

id  customer count
2   john     34
45  Anna      8
2   john     12
8   Pepe     22
2   john     NULL
45  Anna     NULL
8   Pepe     NULL
43  Mark     NULL
1   Alice    NULL

所需的输出是:

id  customer count
2   john     34
45  Anna      8
2   john     12
8   Pepe     22
43  Mark     NULL
1   Alice    NULL

因此,第二个查询应该只使用id而不是UNION从第一个查询中提取不同LEFT JOIN的行!

伪示例:

SELECT * FROM (
  SELECT tbl2.id,tbl2.customer,count from tbl1
  JOIN tbl2 ON tbl2.id = tbl1.id
) a

UNION

SELECT * FROM (
  select id,costumer,NULL as 'count' from tbl1  
) b

WHERE a.id != b.id

我知道我可以使用LEFT JOIN。以上可能吗?

3 个答案:

答案 0 :(得分:1)

也许使用NOT EXISTS

SELECT tbl2.id, tbl2.customer, count
FROM tbl1
INNER JOIN tbl2
    ON tbl2.id = tbl1.id

UNION ALL

SELECT id, costumer, NULL AS 'count'
FROM tbl1
WHERE NOT EXISTS (
        SELECT 1
        FROM tbl2
        WHERE tbl2.id = tbl1.id
        );

即使我没有看到不使用LEFT JOIN的理由,这也是其目的。

答案 1 :(得分:0)

SELECT tbl1.id,
        tbl1.customer,
        (select count from tbl2 where tbl2.id = tbl1.id) as count
from tbl1

编辑:

这段代码带来了ID和CUSTOMER,它们通过你在两个表中的方式和第三列中的一个子选择来从表2中获取数据,记住子选择可能非常耗时并且会延迟查询。

答案 2 :(得分:0)

SELECT * FROM(SELECT tbl2.id,tbl2.customer,count from tbl1
JOIN tbl2 ON tbl2.id = tbl1.id
WHERE tbl2.customer = @customer) AS table_1 /*parameter*/

UNION

/*select all customers*/
select id,costumer,NULL as 'count' from table_1