简体   繁体   English

Mysql查询选择具有不同列值的结果

[英]Mysql Query Selecting Results With A Distinct Column Value

I have a table that displays books. 我有一张展示书籍的桌子。 However I would like only only 1 book to be shown per unique email address ( strContactEmail ). 但是,我希望每个唯一的电子邮件地址( strContactEmail )只显示一本书。 I tried the below query, it didn't work. 我尝试了下面的查询,它没有用。 Any help greatly appreciated.` 任何帮助非常感谢

$sql =  "SELECT lngbookid, strTitle, strAuthor, strcoursecode, strISBN, ".
        " strcontactname, DISTINCT(strContactEmail) AS strContactEmail, ".
        " curPrice, ysnsalerent, dtmpostdate, memcomments, school, ".
        " ASIN, BookIMG, ISBN10, ISBN13, Updated, ".
        " datetime, user_ip, NoOtherBooks ".
        " FROM tblbooks ".
        " WHERE strcoursecode LIKE '%$search%'  ".
        " ORDER BY datetime DESC LIMIT 50";

The easiest way: 最简单的方法:

 
 
 
 
  
  
  SELECT max(lngbookid) as lngbookid, max(strtitle) as strtitle, max(strauthor) as strauthor, max(strcoursecode) as strcoursecode, max(strisbn) as strisbn, max(strcontactname) as strcontactname, strcontactemail, max(curprice) as curprice, max(ysnsalerent) as ysnsalerent, max(dtmpostdate) as dtmpostdate, max(memcomments) as memcomments, max(school) as school, max(asin) as asin, max(bookimg) as bookimg, max(isbn10) as isbn10, max(isbn13) as isbn13, max(updated) as updated, max(datetime) as datetime, max(user_ip) as user_ip, max(nootherbooks) as nootherbooks FROM tblbooks WHERE strcoursecode LIKE '%$search%' GROUP BY strcontactemail ORDER BY datetime DESC LIMIT 50
 
 
  

EDIT Well, the above was actually too "dummy". 编辑嗯,上面实际上太“假”了。 Better way to do this is (providing that column "lngbookid" is a primary key): 更好的方法是(提供列“lngbookid”是主键):

SELECT a.lngbookid,
       a.strtitle,
       a.strauthor,
       a.strcoursecode,
       a.strisbn,
       a.strcontactname,
       a.strcontactemail,
       a.ontactemail,
       a.curprice,
       a.ysnsalerent,
       a.dtmpostdate,
       a.memcomments,
       a.school,
       a.asin,
       a.bookimg,
       a.isbn10,
       a.isbn13,
       a.updated,
       a.datetime,
       a.user_ip,
       a.nootherbooks
FROM   tblbooks AS a
       JOIN (SELECT strcontactemail,
                    Max(lngbookid) AS lngbookid
             FROM   tblbooks
             GROUP  BY strcontactemail) AS b
         ON ( a.strcontactemail = b.strcontactemail
              AND a.lngbookid = b.lngbookid )  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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