Reputation: 81
I have a product table with id ,name ,price and cart table with id ,user_id ,product_id ,qty.
I want all data in product table and related data in cart table where user_id is logged user_id.If no relation with cart i should get data in product table.
Table structure like this:
Upvotes: 0
Views: 91
Reputation: 9018
Based on your example I think you want something like:
create table product (
id int(9) not null auto_increment,
name varchar(20),
Primary key id(`id`)
);
insert into product values (1,'mobile'),(2,'tv'),(3,'fridge');
create table cart (
id int(9) not null auto_increment,
product_id int(9) ,
qty int(9) ,
user_id int(9) ,
Primary key id(`id`)
);
insert into cart values (1,1,1,1),(2,1,1,2);
And you should use:
select p.*,c.* from product p left join cart c on p.id=c.product_id and c.user_id=1;
Upvotes: 1