简体   繁体   中英

SQL select all using JOIN

I'm using this query to collate two sets of results but I now need to use JOIN instead of UNION to get the second part of the data from another table.

However I need quite a lot of fields and can't seem to find a way to maintain the use of SELECT * when using JOIN.

mysql_query("SELECT * FROM table.products WHERE category='$cat'  GROUP BY product_id ORDER BY id UNION ALL SELECT * FROM table.products WHERE  type='red' GROUP BY product_id ");

Table - products

product_id | title    | category | id
0            one         home      10
1            two         home      11
1            two - a     home      12
2            three       work      13

Table - product_details

product_id | type | size |
0            blue   S
1            blue   M
1            red    L

Ultimately I need to list every product in the first table for a given category eg home, as there is sometimes two entries or more for a single product id, I need to only select one row for each product id value. I also need to join the second table so I can get the size info, however I must be able to get the size info by preferring a type eg red.

So for this example I would get a list like:

 product_id  | title    | category | type | size
 0             one        home       blue    S
 1             two        home       red     L

This excludes product_id 2 as it's not in the home category, the first entry for product_id equaling 1 is selected because of the GROUP BY and ORDER BY and the information on size for product_id 1 is L because it is of type red not blue.

Your query can be simplified like below since you are using the same table table.products . Not sure why you need to UNION them.

SELECT * FROM table.products 
WHERE category='$cat' 
and type='red'
GROUP BY product_id  

EDIT:

With your edited post, the query should look like

select p.product_id,p.title,p.category,q.type,q.size
from products p join product_details q
on p.product_id = q.product_id
where p.category =  'home'
and q.type = 'red'

Assuming you are using MySQL, you want a join with an aggregation or aggressive filtering. Here is an example using join and aggregation :

select p.product_id, p.title, p.category,
       substring_index(group_concat(pd.type order by pd.type = 'red' desc, pd.type), ',', 1) as type,
       substring_index(group_concat(pd.size order by pd.type = 'red' desc, pd.type), ',', 1) as size
from products p join
     product_details pd
     on p.product_id = qpd.product_id
where p.category =  'home'
group by p.product_id;

The expression substring_index(group_concat(. . .)) is choosing one type (and one size ) with precedence given to the red type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM