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查询是:
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"
答案 0 :(得分: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
答案 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