2013-06-04 65 views
0

我有三個表* book_category,books和book_pictures *在我的mysql中。我想獲得每本書類別的最新書籍訂單通過修正。我使用這個查詢來獲取最新的書籍,它工作正常。從每個類別的多個表中選擇最新的記錄

select * from (select * from books ORDER BY amended DESC) AS x GROUP BY book_sub_category_id 

,但我想加入我的book_pictures表,所以我得到book_pictures URL來顯示圖像的書。如何編寫查詢以從book_pictures表中獲取最新書籍的URL?下面我告訴你表的結構。

 book_category 
+-------------+-----------------+ 
|category_id | category_name | 
|-------------------------------|    
| ca  | custom Act | 
| ct  | Custom Tarif | 
|-------------+-----------------+ 

          books 
+-------------+-----------------+-----------------+--------------------------+ 
| book_id | category_id | name   |  amended   | 
|-------------------------------|-----------------+--------------------------|    
| 01  |  ca   | custom Act  |  01-06-2011   | 
| 02  |  ca   | custom Act  |  01-06-2012   | 
| 03  |  ca   | custom Act  |  01-06-2013   | 
| 04  |  ct   | custom tarif |  01-07-2011   | 
| 05  |  ct   | custom tarif |  01-07-2012   | 
| 06  |  ct   | custom tarif |  01-07-2013   | 
+-------------+-----------------+-----------------+--------------------------+ 

           book_pictures 
+-------------+-----------------+-----------------+--------------------------+ 
| picture_id | book_id  | small_url  |  large_url   | 
|-------------------------------|-----------------+--------------------------|    
| p1  |  01   |  url  |  url     | 
| p2  |  02   |  url  |  url     | 
| p3  |  03   |  url  |  url     | 
| p4  |  04   |  url  |  url     | 
| p5  |  05   |  url  |  url     | 
| p6  |  06   |  url  |  url     | 
+-------------+-----------------+-----------------+--------------------------+ 
+0

你怎麼定義最新?通過book_id? – Pirion

+0

按日期排列。 – user2087078

回答

1

使用左加入,

我認爲這會工作,也沒有壽運行它。

SELECT * FROM (
       SELECT b.*, 
         p.large_url 
       FROM  books b 
        LEFT JOIN book_pictures p 
         ON b.book_id = p.book_id 
       ORDER BY b.amended DESC 
       ) AS x 
GROUP BY book_sub_category_id 
+0

非常感謝。 – user2087078

+0

感謝編輯@TNK。更容易看到:) – flote

+0

OEDER BY不起作用。當我將ORDER BY b.amended DESC更改爲ORDER BY b.amended ASC時,我得到與降序相同的結果。我不知道這是否發生,爲什麼Order BY不起作用? – user2087078

相關問題