2011-11-08 35 views
2
products 
id   product_cat_id   product_type_id   title  ordering 
1    42      1     "a"   1 
2    42      1     "b"   2 
3    42      2     "c"   1 
4    43      1     "d"   1 

product_cats 
id    title    ordering 
1    "n"     1 
2    "b"     2 
3    "h"     3 


product_types 
id    title    ordering 
1    "b"     1 
2    "n"     2 
3    "m"     3 

我的SQL查詢是這樣的:SQL查詢訂購和使用GROUP BY

SELECT 
`products`.`title`, 
`product_types`.`title` 
FROM 
`products`, 
`product_cats`, 
`product_types` 
WHERE 
`products`.product_cat_id=42 
ORDER BY `product_types`.`ordering`,`products`.`ordering` ASC 

但我的SQL查詢返回的所有標題甚至不具備等於product_cat_id到42我試着用GROUP_BY並且仍然不成功。

我要尋找這樣的:

product_title   product_type_title 
    "a"      "b" 
    "b"      "b" 
    "c"      "n" 

回答

2
SELECT p.title AS product_title, pt.title AS product_type_title 
FROM products p 
INNER JOIN product_types pt 
    ON p.product_type_id = pt.id 
WHERE p.product_cat_id = 42 
ORDER BY pt.ordering, p.ordering 
+0

+1爲正確答案,而走樣表。 –

0
SELECT 
    `products`.`title`, 
    `product_types`.`title` 
FROM 
    `products` 
INNER JOIN 
    `product_types` ON `products`.`product_type_id` = `product_types`.`id` 
WHERE 
    `products`.product_cat_id=42 
ORDER BY 
    `product_types`.`ordering`,`products`.`ordering` ASC