views:

219

answers:

2

Hi,

I want to get some results via query simillar to:

SELECT * FROM users LEFT JOIN IF (users.type = '1', 'private','company') AS details ON users.id = details.user_id WHERE users.id = 1

Any ideas?

+3  A: 
SELECT
  users.*,
  details.info,
  CASE users.type WHEN '1' THEN 'private' ELSE 'company' END AS user_type
FROM
  users
  INNER JOIN (
    SELECT user_id, info FROM private
    UNION
    SELECT user_id, info FROM company
  ) AS details ON details.user_id = users.id

EDIT: Original version of the answer (question misunderstood):

SELECT
  *, 
  CASE type WHEN '1' THEN 'private' ELSE 'company' END AS details
FROM
  users
WHERE
  users.id = 1
Tomalak
It's not exactly what I want.private and company are two diferent tables, which I want to Join: when user.type == 1 I want JOIN private ON user.id = private.user_idand when user.type == 2 I want JOIN company ON user.id = company.user_id
plugowski
@plugowski: See changed answer.
Tomalak
+2  A: 
SELECT * FROM users 
LEFT JOIN private AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type = 1

UNION

SELECT * FROM users 
LEFT JOIN company AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type != 1

I think that is what you are trying to do, isn't it?

As you have now said that the number of columns differs, you would need to specify the columns, e.g.

SELECT 'private' AS detailType, users.*, col1, col2, col3, '' FROM users 
LEFT JOIN private AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type = 1

UNION

SELECT 'company', users.*, col1, '', '', col4  FROM users 
LEFT JOIN company AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type != 1

In this example, private has columns col1, col2 and col3, whilst company has col1 and col4, but you want them all.

Cez
I don't know why now i've get#1222 - The used SELECT statements have a different number of columns
plugowski
if I use only one part of code ie. SELECT * FROM users LEFT JOIN private AS details ON users.id = details.user_id WHERE users.id = 1 AND users.type = 1but if i use UNION I've get error #1222
plugowski
If you have a different number of columns in the two tables (private and company) then you will need to specify the same number of columns in the SELECT. You can fill the blanks using NULL, '', or whatever you want.
Cez
But it's no sense. If I have ie. 5000 records on private and only 2 in company so i must create 4998 empty records?
plugowski
No, assuming that by records you mean rows, the number of columns must match. I'm hoping that you don't have 5000 columns in a table!
Cez
Aaaaaaaa, ok, my bad... So if i have 17 columns on private and only 6 on company i should create "fake_columns"?
plugowski
U R awsome! It works :D Thank a lot!
plugowski
Yes, you would need "fake" columns, but I'm guessing that you've found that out. Glad to help
Cez