Mysql 使用别名合并两个查询,其中条件按别名
以下面的查询为例:Mysql 使用别名合并两个查询,其中条件按别名,mysql,sql,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 上述查询将输
/*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
因此,第二个查询应该使用UNION
,而不是左联接,从第一个查询中仅提取具有不同id
的行
伪示例:
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
我知道我可以用左键连接。上述情况是否可能?可能使用的不存在
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
);
即使我认为没有理由不使用左连接
,这也是它的目的
SELECT tbl1.id,
tbl1.customer,
(select count from tbl2 where tbl2.id = tbl1.id) as count
from tbl1
编辑:
这段代码带来了ID和CUSTOMER,按照您在两个表中的方式,在第三列中都是这样从表2中获取数据的子选择,记住子选择可能会很耗时并延迟查询。为什么不使用左连接
?这是实现这一点的正确方法。虽然此代码可以回答问题,但提供有关此代码回答问题的原因和/或方式的其他上下文可以提高其长期价值。@Ajean,编辑答案,beter now?任何建议都可以自由提出。
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