简体   繁体   中英

what is wrong with this sql query that used order by and left join together? Is this the right way to do it?

SELECT ts.contact_id as contact_id,  ts.contact_name as name ,  ts.is_contact_active  as is_active, ts.created_at,ts.updated_at 
FROM tb_summary ts 
ORDER by created_at 
LEFT JOIN  (tcs.contact_address as address FROM tb_contacts tcs)  ON tcs.contact_id = ts.contact_id
WHERE ts.business_owner_id = ? AND ts.is_contact_active = ?  

This query throws

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN tcs.Contact_address as address, tcs.Contact_id FROM tb_Contacts tcs ' at line 2

Your syntax is way off. A query takes only one from clause, that may contain multiple join s. And the order by clause goes at the end.

So:

SELECT 
    ts.contact_id as contact_id,  
    ts.contact_name as name,  
    ts.is_contact_active as is_active, 
    ts.created_at,ts.updated_at, 
    tc.contact_address as address
FROM tb_summary ts 
LEFT JOIN tb_contacts tc ON tc.contact_id = ts.contact_id 
WHERE ts.business_owner_id = ? AND ts.is_contact_active = ?
ORDER by ts.created_at 

A SELECT statement consists of a sequence of clauses. Your query has four clauses:

  • SELECT
  • FROM
  • WHERE
  • ORDER BY

These operators must be in this order.

JOIN is an operator in the FROM clause. So, it should be structure more like this:

SELECT ts.contact_id as contact_id,  ts.contact_name as name,  ts.is_contact_active  as is_active, ts.created_at, ts.updated_at
FROM tb_summary ts LEFT JOIN 
     tcs.contact_address address tca
     ON tca.contact_id = ts.contact_id
WHERE ts.business_owner_id = ? AND ts.is_contact_active = ?  
ORDER by created_at 

From what I can tell, the query is still non-sensical. The contact_address table is not being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM