0

私は本を​​表示するテーブルを持っています。ただし、一意の電子メール アドレス ( ) ごとに 1 冊の本のみを表示したいと考えていますstrContactEmail。以下のクエリを試しましたが、うまくいきませんでした。どんな助けでも大歓迎です。

$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";
4

2 に答える 2

1

GROUP BY ステートメントを試してください。

http://www.w3schools.com/sql/sql_groupby.asp

于 2012-09-17T14:17:09.003 に答える
1

最も簡単な方法:

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 

編集 さて、上記は実際にはあまりにも「ダミー」でした。これを行うより良い方法は次のとおりです (列「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 )  
于 2012-09-17T14:29:21.903 に答える