简体   繁体   中英

mysql INNER_JOIN subquery

I have inherited a MySQL database, that has a table as follows:

mysql> describe stock_groups;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| group  | varchar(5)   | YES  |     | NULL    |                |
| name   | varchar(255) | YES  |     | NULL    |                |
| parent | varchar(5)   | YES  |     | NULL    |                |
| order  | int(11)      | YES  |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

When I run mysql> select * from stock_groups where group ='D2';

I get:

mysql> select * from stock_groups where `group`='D2';
+----+-------+------+--------+-------+
| id | group | name | parent | order |
+----+-------+------+--------+-------+
| 79 | D2    | MENS | D      |    51 |
+----+-------+------+--------+-------+
1 row in set (0.00 sec)

and also i have a table:

mysql> describe stock_groups_styles_map;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| group | varchar(5)  | NO   |     | NULL    |                |
| style | varchar(25) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

when I run:

mysql> select `group` from stock_groups_styles_map where style='N26';
+-------+
| group |
+-------+
| B1    |
| B11   |
| D2    |
| V2    |
+-------+
4 rows in set (0.00 sec)

how do i get the stock_groups.name ?

Join the tables, and select only the data you need. If you need unique rows, use the distinct keyword:

select  -- If you need unique names, use "select distinct" instead of "select"
    sg.name
from
    stock_groups_styles_map as sgs
    inner join stock_groups as sg on sgs.group = sg.group
where 
    sgs.style = 'N26'

You could also solve this using subqueries, but that would be rather inneficient in this case.

Something important

You should add the appropriate indexes to your tables. It will improve the performance of your database.

You can use inner join on group column

SELECT ss.group, sg.name from 
stock_groups sg inner join stock_groups_styles_map ss on ss.group = sg.group 
where ss.style='N26' 
SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style ='N26';

为我工作。

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