mysql - SQL query to select distinct rows from left table after inner join to the right table -


i have 2 mysql tables. first 1 [products] (primary = id):

[id] | title | description 

and second [sizes] (primary = id & size):

[id] | [size] 

size can have values [1,2,3,4,5,6].

i have php array has size values. reshape comma-separated values string this:

$size_list = implode(",", $sizes); 

for not familiar php, above code generate string this: "1,4,5" , query database this:

$query = "select t1.id,t1.title,t1.description,t2.size products t1 inner join sizes t2 on t1.id=t2.id size in(".$size_list .")"; 

but query replicates products each size have in sizes table. want to:

return records products table have @ least 1 available size in sizes table, without duplicate

and of course

want sizes in variable show client


for example:

products:

1 | product1 | description1 2 | product2 | description2 3 | product3 | description3 4 | product4 | description4 

sizes:

1 | 1 1 | 2 1 | 4 1 | 5 2 | 1 2 | 5 

given $sizes_list="1,2", want output is:

1 | product1 | description1 | 1,2,4,5 2 | product2 | description2 | 1,5 

your query should like:

$query = "     select t1.id, t1.title, t1.description, group_concat(t2.size separator ",") sizes     products t1        inner join sizes t2 on t1.id=t2.id     t1.id in (select t3.id sizes t3 t3.size in (".$size_list .")     group t1.id, t1.title, t1.description " 

a bit of explanation. when join 2 tables, rows table sizes id table products, id = 1 joined 4 records , id = 2 joined 2 records. have aggregate numbers 1 record.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -