Mysql multi-Table query is a common problem. The following describes how to implement Mysql multi-Table query, we hope you can learn more about Mysql multi-table queries.
Multi-Table query:
- CREATE TABLE IF NOT EXISTS contact(
- contact_id int(11) NOT NULL AUTO_INCREMENT,
- user_name varchar(255),
- nom varchar(255),
- prenom varchar(255),
- mail varchar(64),
- passcode char(64),
- PRIMARY KEY(contact_id)
- );
- CREATE TABLE IF NOT EXISTS droit(
- droit_id int( 11 ) NOT NULL AUTO_INCREMENT ,
- droit varchar(255),
- PRIMARY KEY(droit_id)
- );
- CREATE TABLE IF NOT EXISTS contactdroit(
- contactdroit_id int(11) NOT NULL AUTO_INCREMENT,
- contact_id int( 11 ),
- droit_id int( 11 ),
- PRIMARY KEY( contactdroit_id )
- );
- Insert into contact(contact_id, user_name) values(1,'user1');
- Insert into contact(contact_id, user_name) values(2,'user2');
- Insert into contact(contact_id, user_name) values(3,'user3');
- Insert into droit(droit_id, droit) values(1,'admin');
- Insert into droit(droit_id, droit) values(2,'superuser');
- Insert into contactdroit(contact_id, droit_id) values(1, 1);
- Insert into contactdroit(contact_id, droit_id) values(2, 1);
- Insert into contactdroit(contact_id, droit_id) values(3, 2);
-
- SELECT c.contact_id, d.droit_id, d.droit FROM contact c, contactdroit cd, droit d
- where c.contact_id = cd.contact_id
- and cd.droit_id = d.droit_id;
-
Result:
- contact_id droit_id droit
- 1 1 admin
- 2 1 admin
- 3 2 superuser
Example of Multi-table join query:
Both methods can be used, and inner join on is better. The table structure is not pasted out, but it is easy to understand.
Simple Method:
- select c.nom, e.nom
- from consultant c, affaire a, besoin b, salarie sa, site s, entreprise e
- where c.consultant_id=a.consultant_id and a.besoin_id=b.besoin_id and b.salarie_id=sa.salarie_id and ssa.site_id=s.site_id and s.entreprise_id=e.entreprise_id
-
Inner join method:
- select c.nom, e.nom
- from consultant c
- inner join affaire a on c.consultant_id=a.consultant_id
- inner join besoin b on a.besoin_id=b.besoin_id
- inner join salarie sa on b.salarie_id=sa.salarie_id
- inner join site s on ssa.site_id=s.site_id
- inner join entreprise e on s.entreprise_id=e.entreprise_id
-
Restrictions on Functions of MySQL partition tables
MySQL Stored Procedure for table splitting
In-depth discussion on MySQL Lock Mechanism
Detailed description of MySQL Data Table types
Implementation of MySQL fuzzy query with multiple fields in a single table