我是Knex.js查询构建器的新手,我目前在某个简单的MySQL选择方面遇到了麻烦。这是:
SELECT orders.*, IFNULL(x.unread, 0) AS unread_messages
FROM orders
LEFT JOIN
(SELECT id_order, COUNT(*) AS unread
FROM chats
WHERE read_by_user = 0
GROUP BY id_order) AS x
ON x.id_order = orders.id_order
WHERE id_customer = 42
ORDER BY date_submitted;
我有点失去了阅读Knex的文档,但是我应该使用 .joinRaw 进行连接,使用 knex.raw 进行ifnull命令吗?
答案 0 :(得分:4)
https://runkit.com/embed/1olni3l68kn4
knex('orders')
.select(
'orders.*',
knex.raw('IFNULL(??, 0) as ??', ['x.unread', 'unread_messages'])
)
.leftJoin(
knex('charts')
.select('id_order', knex.raw('count(*) as ??', ['unread']))
.where('read_by_use', 0).groupBy('id_order').as('x'),
'x.id_order',
'orders.id_order'
)
.where('id_customer', 42)
.orderBy('date_submitted')
产生
select
`orders`.*, IFNULL(`x`.`unread`, 0) as `unread_messages`
from `orders`
left join (
select `id_order`, count(*) as `unread`
from `charts`
where `read_by_use` = ?
group by `id_order`
) as `x`
on `x`.`id_order` = `orders`.`id_order`
where `id_customer` = ?
order by `date_submitted` asc
答案 1 :(得分:1)
对于那些降落在这里的人:在@Mikael的帮助下,这是我的工作解决方案。
getauxval