tags:

views:

38

answers:

1

I want to use a JOIN to return a boolean result. Here's an example of the data...

t1

id | data 
-----------
1  | abcd     
2  | 2425     
3  | xyz  

t2

id | data | t1_id |
-------------------------
1  | 75   |     2     |    
2  | 79   |     2     |    
3  | 45   |     3     |

So with these two tables I want to select all the data from t1, and also whether a given variable appears in t2.data for each id.

So say the variable is 79, the results should be

id |  data  |  t2_boolean
--------------------------
1  |  abcd  |  0    
2  |  abcd  |  1    
3  |  xyz   |  0

So I'm thinking some sort of join is needed, but without a WHERE clause. I've been banging my head about this one. Is it possible? I really need it inside the same statement as I want to sort results by the boolean field.

As the boolean needs to be a field, can I put a join inside of a field?

Thanks...

+2  A: 

You might have to do a bit of work to knock this into a format suitable for MySQL but does this help?

SELECT t1.id, t1.data, t2.id IS NOT NULL AS t2_boolean
FROM t1
LEFT OUTER JOIN t2 on t1.id = t2.id AND t2.data = 79
Martin Smith
+1: Faster than me
OMG Ponies
Hopefully it's suitable for MySQL though!
Martin Smith
I deleted my answer since it used the wrong join, but it's probably worth mentioning that you can just do `t2.id IS NOT NULL AS t2_boolean` instead of using a CASE
Michael Mrozek
@Martin: MySQL has supported ANSI `CASE` since 5.0: http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
OMG Ponies
@Michael and @OMG Ponies Thanks. I've updated mine accordingly.
Martin Smith
Thanks so much, that works perfectly.