0

I have 2 tables: files and user.

files
----------------------------
|Fileid  | name  | type    |
----------------------------
| 01     | file1 | private |
| 02     | file2 | private |
| 03     | file3 | Public  |
----------------------------

and

user
---------------------
| Fileid  | UserId  |
---------------------
| 01      | user1   | 
| 02      | user1   |
---------------------

How would I select all the record(private and public) for who ever id is in the 'user' table and only 'public' files for any other user where the 'userid' is not in the 'user' table? please help

1
  • this question is strangely formatted and confusingly described. Commented Oct 22, 2011 at 18:39

2 Answers 2

2

If I correctly understand the problem, you are looking for a LEFT JOIN favoring files returning all fields for non-null UserId, or Public only when UserId IS NULL.

SELECT 
  files.*
FROM files LEFT JOIN user ON files.Fileid = user.Fileid
WHERE 
  user.UserId IS NOT NULL
  OR (user.UserId IS NULL AND files.type = 'Public')
Sign up to request clarification or add additional context in comments.

5 Comments

i think this is the solution which i was looking for,let me try and see.Thanks @Michael
That query would do the trick, except for that you have a typo in your parenthesis; user.User.Id should be user.UserId
@Marcus Just fixed as you were commenting.
Hi @Michael ,its not really working ... can it be because of user.UserId IS NOT NULL" ?
got it working after changing the field to be null able ,thank you
0

From what I understand you need 2 loops for the first part. one loop will get the user IDs from the table. and the second loop should be placed inside the first one. the second will use the ID in the loop to get all the files.

Second part can be done by having a loop with a sql query like SELECT * FROM files WHERE userID != $userID[$i] and $userID should be an array with all of your users ID.

NOTE : I assumed that you forgot to include a foreign key in the files table to connect both tables together.

2 Comments

Ahoura Ghotbi,thanks for the reply...is there a way i can do it in the query itself?
Yea if I am not mistaking you can use the union function in SQL and get all the IDs and then compare them with your other table to see if they are there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.