简体   繁体   中英

My first SQL Query - OrderBy error

I am using a MySQL query to get information from two tables and then ordering them by one field. Something about the last line is not working and the AJAX function that loads the content returns an error.

$list = mysql_query("SELECT    id, 
           user_email, 
           meta_lastname.meta_value lastname,  
           meta_firstname.meta_value firstname 
 FROM      wp_users 
 LEFT JOIN wp_usermeta meta_lastname 
 ON        meta_lastname.user_id = wp_users.id 
 LEFT JOIN wp_usermeta meta_firstname 
 ON        meta_firstname.user_id = wp_users.id 
 WHERE     meta_lastname.meta_key = 'last_name' 
 AND       meta_firstname.meta_key = 'first_name'
    WHERE user_email LIKE '%$searchpattern%' 
    ORDER BY lastname;");

Something about this last bit is not right and is returning an error.

WHERE user_email LIKE '%$searchpattern%' 
        ORDER BY lastname;");

Any ideas on whats gone wrong?

Marvellous

You have two WHERE in your query:

 WHERE     meta_lastname.meta_key = 'last_name' 
 AND       meta_firstname.meta_key = 'first_name'
    WHERE user_email LIKE '%$searchpattern%' 

You need to use a logical operator like AND :

 WHERE     meta_lastname.meta_key = 'last_name' 
 AND       meta_firstname.meta_key = 'first_name'
    AND user_email LIKE '%$searchpattern%' 

Also, you probably have to order by the original name meta_lastname.meta_value not the alias lastname .

按完整列名排序,而不是别名。

ORDER BY meta_lastname.meta_value

I guess it's the semicolon. Try ORDER BY lastname"); Else try without the order statement.

您还需要将第二个“ WHERE”更改为“ AND”。

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