tags:

views:

64

answers:

5
+1  Q: 

mysql, using if

I have this sql query:

...
LEFT JOIN users ON
users.id = mod.id and mod.level = 1
...

But if don't found any result with mod.level = 1, i wish search with mod.data > 1 (users.id = mod.id and mod.data > 1)

+1  A: 

You can switch your and to a WHERE and use an OR funtion:

LEFT JOIN users ON
users.id = mod.id 
WHERE mod.level = 1
OR mod.data > 1
Scott's Oasys
This is more easily written `where modl.level >= 1`, but this will return rows for both `mod.level = 1` and `mod.data > 1`. It seems the OP only want rows where `mod.data > 1` if there are **no** rows where `mod.level = 1`.
RedFilter
+1  A: 

You can additionally filter on the JOIN like this:

LEFT JOIN users ON users.id = mod.id AND (mod.level = 1 OR mod.data > 1)
the_void
This is more easily written `modl.level >= 1`, but this will return rows for both `mod.level = 1` and `mod.data > 1`. It seems the OP only want rows where `mod.data > 1` if there are **no** rows where `mod.level = 1`.
RedFilter
A: 

Try something like this:

select *
from MyTable m
left outer join (
    select id
    from MyTable
    where level = 1
) ml on m.id = ml.id
left outer join users u on m.id = u.id
    and (u.id = m1.id or (m1.id is null and m.level > 1))
RedFilter
A: 

It may be slow but the join returns all rows that fit either case. Then uses the where clause to filter out the rows you don't want.

Select *
From 
  LEFT JOIN users ON users.id = mod.id AND (mod.level = 1 OR mod.data > 1) 
Where
  Case
    When mod.level = 1 then 1 
    When Not Exists(Select 1 from users Where users.id = mod.id and mod.level=1) 
      AND mod.data > 1 then 1
    Else 0 END = 1;
Bill
You are missing a table name after `From`. Additionally, `AND (mod.level = 1 OR mod.data > 1)` is more simply written as `AND mod.level >= 1`.
RedFilter
+1  A: 

maybe using a XOR?

...
LEFT JOIN users
       ON users.id = mod.id
    WHERE mod.level = 1
      XOR mod.data > 1
...

this will get rows where mod.level is 1 or mod.data is greater than 1, but not rows where level is 1 and data is greater 1 at the same time

if you only want to look at mod.data when mod.level is not 1 use the following condition:

...
WHERE mod.level = 1
   OR (mod.level != 1
  AND mod.data > 1)
...
knittl
I don't think this works the way you expect. The XOR will not examine multiple rows at once, which I think is what the OP needs. Your second example is more simply written as `where mod.level >= 1`.
RedFilter