suppose we have two tables users
and products
table users
has an accountBalance column
table users
schema:
userId accountBalance .........
1 500 .........
2 45000 .........
3 4238827 .........
. . .........
. . .........
. . .........
table products
has a price column
table products
schema:
productId price .........
1 40000 .........
2 55000 .........
3 90000 .........
. . .........
. . .........
. . .........
these table don't have any relation so i can't join them by a common key. What i want to know is to find out what products each user can buy and format it as the expected result following:
the expected result
is:
userId productIdsUserAffordToBuy
1 NUll
2 1*2
3 1*2*3
. .
. .
. .
Using GROUP_CONCAT()
to create a list inside a single column and joining against the condition accountBalance >= price
you can in fact perform a LEFT JOIN
(necessary to return NULL
for the user who can't afford anything, rather than omitting the row):
SELECT
userId,
GROUP_CONCAT(productId) AS productIdUserAffordToBuy
FROM
users
LEFT JOIN products ON users.accountBalance >= products.price
GROUP BY userId
select userid,accountbalance,group_concat(productid) as productaffordtobuy
from users cross join products
where price<=accountbalance
group by userid
SQL FIDDLE HERE>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With