简体   繁体   中英

distinct not working in sql query

i have two tables in my db .. one is Messages and the other is Contacts ... both tables contain the mobile_number field.. in Contacts table there is no duplicate numbers ... but in Messages tables there are several duplicate numbers in mobileNo field...what i am doing is write now i am selecting the distinct mobile numbers from the Messages tables and then i am comparring the distinct numbers from the contacts table ... so if the messages_mobileNo is found on the contacts table then give me the contact name against the number otherwise messages_mobileNo ... so the problem is distinct not working .. i am not able to get the distinct numbers from the Messages table ... it is showing me the duplicate numbers

here is my query

 SELECT DISTINCT Message.mobileNo,
            Contact.mobileNo,
            Contact.workNo,
            Contact.homeNo,
            Contact.other,
            Contact.name,

            Message.body,
            Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON (Message.user_id = Contact.user_id
                                         AND ((Message.mobileNo = Contact.mobileNo)
                                              OR (Message.mobileNo = Contact.workNo)
                                              OR (Message.mobileNo = Contact.homeNo)
                                              OR (Message.mobileNo = Contact.other)))
 WHERE Message.User_id = 23
 ORDER BY Message.idTextMessage DESC LIMIT 6

So your trying to get the last 6 messages of a person if I'm right?

 SELECT Message.mobileNo,
            Contact.mobileNo,
            Contact.workNo,
            Contact.homeNo,
            Contact.other,
            Contact.name,

            Message.body,
            Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON Message.user_id = Contact.user_id
                                         AND Message.mobileNo IN (Contact.mobileNo, Contact.workNo, Contact.homeNo, Contact.other)
 WHERE Message.User_id = 23
GROUP BY Message.mobileNo
 ORDER BY Message.idTextMessage DESC LIMIT 6

在您的ORDER BY之前添加GROUP BY Message.mobileNo

If you are using MySQL SELECT DISTINCT with an ORDER BY added to it, you will have to create a temporary table where it can store its results. Here is a link offering more help:

MySQL DISTINCT Optimization

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