我从未在sql-query中使用“if-else”或“case”,但我想这次我需要。 我有一个表,其数据代表两个用户之间的竞争:
//properties of "competition-table
int competitionId
int userId_Contrahent1
int userId_Contrahent2
otherdata....
用户可以在该比赛中投票选出一个或另一个违禁者;投票如下所示:
//properties of vote-table
int voteId
int competitionId
int userId_Voter
int userId_Winner // the user for which this vote counts
otherdata....
显然,我的Web应用程序中的每个给定用户只能为任何特定竞争投票一次。因此,当我查询比赛时,如果当前用户(拥有当前会话)已经投票参加本次比赛,我也希望获得相关信息。所以除了竞争的所有其他属性之外,我还想要一个额外的属性,它有一个像“投票”的关键字和一个像“是”或“否”的值。 所以我的select语句应该看起来像这样:
SELECT competition.*,
If EXISTS (
SELECT * FROM vote WHERE userId_Voter = $currentUserId
AND competitionId = competition.competitionId)
...do something
FROM competition;
我如何在MySQL中完全做到这一点?
答案 0 :(得分:3)
SELECT c.*,
IF(v.competitionId IS NOT NULL, 'voted', 'not voted') AS `verdict`
FROM competition c
LEFT JOIN vote v ON v.competitionId = c.competitionId
AND v.userId_Voter = $currentUserId