Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

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

I have two MySQL tables. This is first one [products] (PRIMARY = id):

[id] | title | description

and this is the second [sizes] (PRIMARY = id & size):

[id] | [size]

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

I have a PHP array which has the size values. I reshape it to a comma-separated values string like this:

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

For those who are not familiar with PHP, the above code will generate an string like this: "1,4,5" and then query the database like this:

$query = "SELECT t1.id,t1.title,t1.description,t2.size FROM products t1 INNER JOIN sizes t2 ON t1.id=t2.id WHERE size IN(".$size_list .")";

But this query replicates the products for each size they have in the sizes table. I want to:

Return records from products table which have at least one available size in sizes table, without duplicate

and of course

want those sizes in a variable to show to the 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", what I want as output is:

1 | product1 | description1 | 1,2,4,5
2 | product2 | description2 | 1,5
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your query should be like:

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

A bit of explanation. When you join two tables, you get all rows from table sizes for all id from table products, so id = 1 joined with four records and id = 2 joined with two records. So you have to aggregate this numbers into one record.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...