我使用查询:
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
答案 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
。