开发者

MySql If statements

I have a simple table that logs simple events an administrator does. Nothing complicated.

One of the columns is userid, so I can reference the user's name from the users table:

SELECT u.username FROM `users` u, `history` h WHERE u.userid = h.userid

My issue is that the internal system also logs events (just like a user), but there is no userid related to the internal system. It is simply logged as zero, in the record.

Is there a way to modify the query to reflect this? I've tried a LEFT JOIN, but that doesn't let me specify "system" as the username. The开发者_如何学运维 other thing i can do is enter a new user into the user's table, and call it "Internal System". But I really don't want to do that.

Is it possible to do this from the query level?


Use:

   SELECT COALESCE(u.username, 'SYSTEM') AS username,
     FROM HISTORY h
LEFT JOIN USERS u ON u.userid = h.userid

COALESCE will return the first non-NULL value, so if you LEFT JOIN onto USERS and username is NULL--then "system" or whatever you prefer will appear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜