I have a purchase table and user_id is a foreign key.
If there is user_id in the purchase table, it returns 1,
I want to return 0 if there is none.
I tried using the case statement, but it returns the following result.
{
"data": []
}
Below is the query. Is there any other way? I need help.
dao.js
const getUserPurchase = async(userId) => {
const purchase = await myDataSource.query(
`SELECT
u.id,
CASE
WHEN p.user_id is null
THEN '0'
ELSE '1'
END AS userPurchase
FROM purchase p
JOIN users u ON p.user_id = u.id
WHERE u.id = ?`,
[userId],
);
return purchase;
};
3
Answers
You want to SELECT all users and for those users who have purchased something, that is a corrsponding record in table
purchase
exists, you want to get a 1, for all others a 0.I’d write it this way:
It write its in this way…I am using table name "book" and "bookshelf"
and Status be 0 when book in not available in "bookshelf" table