PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table user_interests (user_id int, product_id int); insert into user_interests values (1, 1), (1, 2), (2, 2); create table shops (id int, name varchar(255)); insert into shops values (604, 'Halle'), (626, 'Vilvoorde'), (605, 'Heverlee'); create table products (id int, name varchar(255)); insert into products values (1, 'Chips'), (2, 'Snacks'), (3, 'Milk'); create table product_prices (product_id int, shop_id int, price decimal(8,2)); insert into product_prices values (1,604, 10),(1,605, 12),(2,604, 5),(2,605, 6),(2,626, 6);
Copy Clear
Copy Format Clear
<?php $sql = "select p.id, p.name product, pp.price, s.name shop from user_interests ui join products p on p.id=ui.product_id join product_prices pp on pp.product_id=ui.product_id join shops s on s.id=pp.shop_id where ui.user_id=1 order by p.id,s.id"; $data = $pdo->query($sql)->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC); foreach ($data as $product) { echo $product[0]['product'],"\n"; foreach ($product as $row) { echo "\t$row[price] $row[shop]\n"; } }
Show:  
Copy Clear