我有以下表格:
CLIENT
- ID
- NAME
- USER
ORDER
- ID
- DATE
- CLIENT_ID
- USER
ORDER_LINE
- ORDER_ID
- LINE_ID
- USER
用户字段跟踪上次修改记录的人员。此外,每个订单项可能会被其他用户修改。
我试图找出一个用户,他们参与了哪些订单。
select
client.id,
client.name,
order.id,
order.date,
case
when order_line.user = :user then 'Line Item'
when order.user = :user then 'Order'
when client.user = :user then 'Client'
end
from
order_line
join order on order_id = order.id
join client on order.client_id = client.id
where
order_line.user = :user
or order.user = :user
or client.user = :user
问题是用户可能会触摸order和order_line表,因此我得到了多个结果。添加select distinct没有帮助,因为case语句的结果在每种情况下都不同。
有没有办法重构查询,所以每个订单只能获得一个结果?
案例陈述的结果并不是那么重要 - 如果我能够在有人触摸两个表但只有“行项目”就行的情况下获得“行项目,订单”会很好。
答案 0 :(得分:0)
oracle是否有像mysql一样的group_concat(或类似的)?
select client_id, name, order_id, date, group_concat(what separator ', ') as changes
from (
select
client.id as client_id,
client.name,
order.id as order_id,
order.date,
case
when order_line.user = :user then 'Line Item'
when order.user = :user then 'Order'
when client.user = :user then 'Client'
end as what
from
order_line
join order on order_id = order.id
join client on order.client_id = client.id
where
order_line.user = :user
or order.user = :user
or client.user = :user
) as part1
group by client_id, name, order_id, date;
答案 1 :(得分:0)
如何连接最后一列并使用distinct,如下所示:
select distinct
client.id,
client.name,
order.id,
order.date,
case when order_line.user = :user then 'Line Item ' else '' end ||
case when order.user = :user then 'Order ' else '' end ||
case when client.user = :user then 'Client ' else '' end
from
order_line
join order on order_id = order.id
join client on order.client_id = client.id
where
order_line.user = :user
or order.user = :user
or client.user = :user
答案 2 :(得分:0)
我建议这个
它将显示用户更改的所有订单以及他是否更改了订单项但未更改订单项
SELECT client.id,
client.name,
order.id,
order.date
FROM order
JOIN
client
ON client_id = client.id
WHERE order.USER = :USER
OR client.USER = :USER
OR :USER IN (SELECT USER
FROM ORDER_LINE OL
WHERE ORDER_LINE.ORDER_ID = ORDER.ID)
答案 3 :(得分:0)
尝试以下内容:
select client_id,
max(client_name),
order_id,
max(order_date),
max(Line_User),
max(Order_User),
max(Client_User)
(select client.id client_id,
client.name client_name,
order.id order_id,
order.date order_date,
case when order_line.user = :user then 'Y' else 'N' end Line_User,
case when order.user = :user then 'Y' else 'N' end Order_User,
case when client.user = :user then 'Y' else 'N' end Client_User
from order_line
join order on order_id = order.id
join client on order.client_id = client.id
where order_line.user = :user or order.user = :user or client.user = :user)
group by client_id, order_id;