Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quering two tables without any relation

Tags:

sql

mysql

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
.       .
.       .
.       .
like image 537
pouya Avatar asked Dec 16 '22 20:12

pouya


2 Answers

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
like image 146
Michael Berkowski Avatar answered Dec 31 '22 04:12

Michael Berkowski


select userid,accountbalance,group_concat(productid) as productaffordtobuy
from users cross join products 
where price<=accountbalance
group by userid

SQL FIDDLE HERE>

like image 24
sel Avatar answered Dec 31 '22 03:12

sel