Search code examples
phpmysqlsortingjoinquery-optimization

MYSQL is this JOIN too verbose or this is the only way? sort not working


I am working on a project using procedural PHP and phpmyadmin with InnoDB engine. I am not a developer, not a professional, I just love having fun with PHP so please keep it in mind if I say something wrong (or if you want to suggest me to use object oriented PHP) :).
I have something like this(just and example, actually I have a lot of linked tables and fields):

request(id, customer_id, field1, contact_id, field2)
customer(id, customer)
contact(id, contact)

I need to return row id=1 in "request" table with referred values (not with id numbers) so my result has to be like: "Company X", value1, value2, "John".

I can get this with:

SELECT * FROM (
    (
    SELECT customer.customer
    FROM customer
    JOIN request ON customer.id=request.customer_id
    WHERE request.id=1
    ) as result1
    JOIN 
    (
    SELECT request.field1, request.field2
    FROM request
    WHERE request.id=1
    ) as result2
    JOIN 
    (
    SELECT contact.contact
    FROM contact
    JOIN request ON contact.id=request.contact_id
    WHERE request.id=1
    ) as result3
)

(I do not know if I can omit the "resultX" aliases but with phpmyadmin I need to have them if not I get an error).

Now my questions:

1- This works but I feel this is not the right way of writing the code, I think it can be achieved in a better/smarter way and with less code, but I do not how.
2- How can I list the results in different order? Like: field2,customer,contact,field1? I tried to split the field1,field2 SELECT and change order in first line like this:

SELECT result2,result1,result4,result3 FROM (
    (
    SELECT customer.customer
    FROM customer
    JOIN request ON customer.id=request.customer_id
    WHERE request.id=1
    ) as result1
    JOIN 
    (
    SELECT request.field1
    FROM request
    WHERE request.id=1
    ) as result2
    JOIN
    SELECT request.field2
    FROM request
    WHERE request.id=1
    ) as result3
    JOIN 
    (
    SELECT contact.contact
    FROM contact
    JOIN request ON contact.id=request.contact_id
    WHERE request.id=1
    ) as result4
)

but it returns: "#1054 - Unknow column 'result2' in 'field list'"

I hope it is all clear, thanks in advance to everyone, and congratulations for one of the most useful pages in the whole Internet :)


Solution

  • You can do multiple joins in the same select

    SELECT customer.customer, request.field1, request.field2, contact.contact
    FROM request 
    JOIN customer ON request.customer_id = customer.id
    JOIN contact  ON request.contact_id = contact.id
    

    You can put the fields on the order you want.