2010-12-03 60 views
1

我从来没有在sql-query中使用过“if-​​else”或“case”,但我想我现在需要。 我有一个表,其数据代表像两个用户之间的竞争:MySQL:检查数据是否存在于查询中

//properties of "competition-table 
    int competitionId 
    int userId_Contrahent1 
    int userId_Contrahent2 
    otherdata.... 

用户可以投票给一个或竞争中的其他contrahent;投票表示,像这样:

//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

创建新列ALTER TABLE tablename ADD cloumnname tinyint(); – Breezer 2010-12-03 03:58:07

+0

@Breezer:我无法添加每个现有的用户在我的webapp的另一列竞争表! – 2010-12-03 04:12:21

回答

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 
相关问题