如何使用UNION选择包括NULL的所有字段?

时间:2016-05-15 17:47:22

标签: mysql sql

我使用查询:

SELECT idFavourite AS entity, 'favourite' AS type 
FROM favourite 
WHERE idCar = 1 AND idUser = 1 
UNION
SELECT idLike AS entity, 'likes' AS type 
FROM `likes` 
WHERE idCar = 1 AND idUserLiked = 2

如果第二个条件不正确,则此查询仅返回一个type。我怎样才能得到两个type两个查询?

新查询:

SELECT likes.idLike AS likes, favourite.idFavourite AS fav FROM favourite

LEFT JOIN `likes` ON (likes.idCar = favourite.idCar) AND (likes.idUserLiked = favourite.idUser) AND
likes.idCar = 1 AND likes.idUserLiked = 2

1 个答案:

答案 0 :(得分:1)

首先,使用union all除非您想要产生删除重复项的开销(在这种情况下这是不可能的)。你可以这样做:

SELECT idFavourite AS entity, 'favourite' AS type
FROM favourite 
WHERE idCar =1 AND idUser = 1
UNION ALL
SELECT idLike AS entity, 'likes' AS type
FROM `likes` 
WHERE idCar = 1 AND idUserLiked = 2
UNION ALL
SELECT NULL, 'likes'
FROM (SELECT 1 as x) t
WHERE NOT EXISTS (SELECT 1 FROM likes WHERE idCar = 1 AND idUserLiked = 2);

或者,如果您只希望第二个子查询中最多有一行,则使用聚合:

SELECT idFavourite AS entity, 'favourite' AS type
FROM favourite 
WHERE idCar =1 AND idUser = 1
UNION ALL
SELECT MAX(idLike) AS entity, 'likes' AS type
FROM `likes` 
WHERE idCar = 1 AND idUserLiked = 2;

没有GROUP BY的聚合查询总是返回一行。在这种情况下,如果entity子句过滤掉所有内容,则NULL将为WHERE