SQL IF / EXISTS语句

时间:2013-05-15 10:44:24

标签: sql if-statement exists

我有两张表可能看起来像这样..

table_gb:

    ID:     Author:        Email:             Login:
    1.      John Doe       john@email.com     1
    2.      Jenn Smith     jenn@email.net     1
    3.      Michael        mich@email.co.uk   0


table_user:

    ID:     Username:      Email:
    1.      Jenstar        jenn@email.net
    2.      Knoxvile       knox@email.org
    3.      JohnDoe        john@email.com`


现在我想要做的就是创建一个SQL语句,从table_gb和IF“Login”== 1中提取所有字段,然后我希望它继续使用table_user中匹配的电子邮件来提取用户名。 。

返回类似的内容..

    ID:     Author:       Username:      Email:               Login:
    1.      John Doe      JohnDoe        john@email.com       1
    2.      Jenn Smith    Jenstar        jenn@email.net       1
    3.      Michael                      mich@email.co.uk     0


它基本上只从table_user获取用户名,但仅在登录设置为1时才有 任何的想法?我基本上都尝试了一切,但似乎没有任何作用!...

2 个答案:

答案 0 :(得分:5)

您应该能够在表之间使用LEFT JOIN,然后使用CASE表达式来显示用户名:

select g.id,
  g.author,
  case when g.login = 1 then u.username else '' end username,
  g.email,
  g.login
from table_gb g
left join table_user u
  on g.email = u.email;

请参阅SQL Fiddle with Demo

答案 1 :(得分:3)

只需使用LEFT JOIN

即可
   SELECT g.ID, g.Author, u.Username, g.Email, g.Login
     FROM table_gb g 
LEFT JOIN table_user u
       ON g.Email = u.EMail;

输出:

╔════╦════════════╦══════════╦══════════════════╦═══════╗
║ ID ║   AUTHOR   ║ USERNAME ║      EMAIL       ║ LOGIN ║
╠════╬════════════╬══════════╬══════════════════╬═══════╣
║  1 ║ John Doe   ║ JohnDoe  ║ john@email.com   ║     1 ║
║  2 ║ Jenn Smith ║ Jenstar  ║ jenn@email.net   ║     1 ║
║  3 ║ Michael    ║ (null)   ║ mich@email.co.uk ║     0 ║
╚════╩════════════╩══════════╩══════════════════╩═══════╝

See this SQLFiddle