views:

36

answers:

3

I have a users table, and a view table which lists some user ids... They look something like this:

Users:

User_ID  |   Name       |   Age   | ...
   555      John Doe        35
   556      Jane Doe        24
   557      John Smith      18

View_Table

User_ID
  555
  557

Now, when I do run a query to retrieve a user:

SELECT User_ID,Name,Age FROM Users WHERE User_ID = 555

SELECT User_ID,Name,Age FROM Users WHERE User_ID = 556

I also would like to select a boolean, stating whether or not the user I'm retrieving is present in the View_Table.

Result:

   User_ID           Name          Age      In_View
    555             John Doe       35         1
    556             Jane Doe       24         0

Any help would be greatly appreciated. Efficiency is a huge plus. Thanks!!

+1  A: 

I would do a LEFT JOIN. So long as you have key/index for User_ID, it should be very efficient.

SELECT User_ID,Name,Age, IF(View_Table.User_ID, 1, 0) AS In_View
FROM Users LEFT JOIN View_Table USING(User_ID)
WHERE User_ID = 555
Jason McCreary
+3  A: 
SELECT 
   User_ID, Name, Age, 
   CASE WHEN v.UserID is not null THEN 1 ELSE 0 END AS In_View
FROM Users u
LEFT JOIN View_Table v on u.User_ID = v.UserID
WHERE UserID ...;
ar
+5  A: 
SELECT Users.User_ID,Name,Age, View_Table.User_ID IS NOT NULL AS In_View
FROM Users 
LEFT JOIN View_table USING (User_ID)
WHERE User_ID = 555
Naktibalda
+1 for the usage of `IS NOT NULL` instead of `IF()`
Jason McCreary