0

I'm trying to do this query. I have these three tables projects id name

authors
    id
    id_user
    fk_id project
    type = author, editor

in Table I have authors who is the creator and who is the editor I'm trying to make a query in mysql where you can see in one record who is the author and publisher.

I do the consultation with one of the two

SELECT p.id_project,p.name_project,a.fk_id_user,a.type,u.name    
FROM projects p,users u, authors a
where p.id_project = a.fk_id_project 
and a.type = 'author' 
and a.fk_id_user = u.id_user

the result is

   id_project, name_proyect, type, user, name_user
    1 ,         bambo,       author, 145, andrea

want is to do this

id_project, name_proyect, type, user, name_user, type2, user2, name_user2
1         ,bambo        , author,145, andrea,   editor, 785,    barack

try to do this but not worked

SELECT p.id_project,p.name_project,a.fk_id_user,a.type,u.name,a.fk_id_user as user2, a.tipo as type2
FROM
projects p, users u, authors to
where p.id_project = a.fk_id_project 
and a.type = 'author' 
and a.fk_id_user = u.id_user 
and user2 = u.id_user 
and Typo2 = 'editor'

That type of query could use or if I'm doing wrong this.

3
  • 1
    Please elaborate on the phrase, "but not worked". What actually happened when you ran that query? Commented May 31, 2013 at 17:46
  • 1
    is projects p, users u, authors to a typo? if not you need to change authors to to authors a Commented May 31, 2013 at 17:49
  • 1
    Also, he says Typo2 instead of type2 Commented May 31, 2013 at 18:00

1 Answer 1

1

suggest using LEFT or INNER JOIN authors a ON blablabla instead of having everything in the WHERE clause. However, try this:

SELECT
p.id_proyecto,
p.nombre_proyecto,
a.tipo,
a.fkidusario,
u.Nombres,
aa.tipo as type2
aa.fkidusario as user2,    
uu.Nombres as name_user2

FROM proyectos p 
JOIN usuarios u 
JOIN usuarios uu 
LEFT JOIN responsables a ON p.id_proyecto = a.fkidproyecto AND a.tipo = 'author' AND a.fkidusario = u.id_usuario 
LEFT JOIN responsables aa ON  p.id_proyecto = aa.fkidproyecto AND aa.tipo = 'editor' AND aa.fkidusario = uu.id_usuario
Sign up to request clarification or add additional context in comments.

4 Comments

+1 to using LEFT JOIN vs putting everything in the WHERE clause. It's tremendously easier to read. I think you should update your example to show joins in action.
Tried, but its hard without the db schema
Updated to match schema, try this :)

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.