我有以下关系:
我想得到:
我在PostgreSql中有以下SQL:
Route::get('/techniciensbytache/{tache_id}',
'TechnicienController@getTechniciensByTache');
我的问题是我不知道限制左连接和排序依据,我尝试添加LIMIT 1
SELECT DISTINCT ON(I.product_id) P.id, P.name, P.short_description,
CAT.short_name AS category, I.url
FROM products_product AS P
LEFT JOIN products_product_categories AS RPC ON P.id = RPC.product_id
LEFT JOIN categories_category AS CAT ON RPC.category_id = CAT.id
LEFT JOIN products_productimage AS I ON I.product_id = P.id
WHERE (P.is_active = TRUE)
但它无效,我收到代码错误LEFT JOIN categories_category AS CAT ON RPC.category_id = CAT.id LIMIT 1
'
类别表
'syntax error at or near "LEFT"
产品表
id | category_name | category_short_name
1 catA A
2 catB B
3 catC C
ManytoMany:product_category
id | product_name | product_desc
1 P1 lorem1
2 P2 lorem2
3 P3 lorem3
图片表
id product_id category_id
1 1 1
2 2 1
3 1 2
4 3 3
5 3 3
对于ID为1的产品,我希望得到:
id url product_id order
1 lo1 1 4
2 lo2 1 0
3 lo3 1 1
4 lo4 2 0
答案 0 :(得分:1)
DISTINCT ON
, ORDER BY
毫无意义。由于您需要两个不同的订单(图片i.order
和类别cat.id
),您必须在单独的子查询中执行此操作。
select p.id, p.name, p.short_description, c.short_name, i.url
from products_product p
left join
(
select distinct on (pcat.product_id) pcat.product_id, cat.short_name
from products_product_categories pcat
join categories_category cat on cat.id = pcat.category_id
order by pcat.product_id, cat.id
) c on c.product_id = p.id
left join
(
select distinct on (product_id) product_id, url
from products_productimage
order by product_id, order
) i on i.product_id = p.id
where p.is_active
order by p.id;
编写此查询的两种方法是: