MySQL从最低ID中选择列

时间:2014-06-13 12:45:54

标签: php mysql

如何从最低ID中选择一列?我想得到kartikelpict,从最低nNr和最低nNr cPfad。

tartikelpict
+--------------+--------------+-------+
| kartikelpict |     cPfad    |  nNr  |
+--------------+--------------+-------+
|     560      | picture4.jpg |   4   |
|     560      | picture3.jpg |   3   |
|     560      | picture2.jpg |   2   |
|     560      | picture.jpg  |   1   |
+--------------+--------------+-------+
|     561      | picture4.jpg |   4   |
|     561      | picture3.jpg |   3   |
|     561      | picture2.jpg |   2   |
|     561      | picture.jpg  |   1   |
+--------------+--------------+-------+

tartikel
+----------+-------+---------------------+------------+-------+
| kArtikel | cName |  cKurzBeschreibung  | dErstellt  | cSeo  |
+----------+-------+---------------------+------------+-------+
|   560    | 12345 |   Short Description | 2014-03-25 | 12345 |
+----------+-------+---------------------+------------+-------+
|   561    | ABCDE |   Short Description | 2014-03-25 | abcde |
+----------+-------+---------------------+------------+-------+

这是我的要求

SELECT 
    p1.kArtikel, 
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad
    FROM tartikel AS p1
    JOIN tartikelpict AS p2 
    ON (p1.kArtikel = p2.kartikelpict)
    JOIN (SELECT kartikelpict, cPfad, MIN(nNr) nNr FROM tartikelpict GROUP BY kartikelpict) p3
    ON(p2.kartikelpict = p3.kartikelpict AND p2.nNr = p3.nNr AND p3.nNr = p3.cPfad)
    ORDER BY p1.kArtikel;

这是我正在调用的PHP代码

while ($row = mysql_fetch_array($result)){ 
    $nNr = $row['nNr'];
    echo "\t\t" . '<link>http://domain/'.$cSeo.'</link>' . "\n";
}

2 个答案:

答案 0 :(得分:0)

cPfad似乎搞乱你的子查询并加入子句。试试这个:

SELECT p1.kArtikel, 
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad
FROM tartikel AS p1
JOIN tartikelpict AS p2  
     ON (p1.kArtikel = p2.kartikelpict)
JOIN (SELECT kartikelpict,  MIN(nNr) min_nNr FROM tartikelpict GROUP BY kartikelpict) p3
     ON (p2.kartikelpict = p3.kartikelpict AND p2.nNr = p3.min_nNr)
ORDER BY p1.kArtikel;

答案 1 :(得分:0)

SELECT x.*
  FROM tartikelpict x
  JOIN 
     ( SELECT kartikelpict
            , MIN(nNr) min_nnr
         FROM tartikelpict 
        GROUP 
           BY kartikelpict
     ) y
    ON y. kartikelpict =  x.kartikelpict
   AND y. min_nnr = x.nnr;