how to fetch data from multiple tables - php

So I normalize my database and it seems quite complicated for me to fetch or update records in tables.
I have 5 tables ( details, country, materials, vendor_countries, vendor_materials). Actually "details" is my main table.
country table have two column (id, name).
materials table also have two column(id, name).
details table have personnel information about vendors (name, email, phone, address).
A vendor could have multiple countries and materials so I made two more tables vendor_countries and vendor_materials and their column are (did,cid), (did,mid).
"did" is the id of each vendor coming from details table and cid,mid is the country id and material id coming from country and material table.
Now I want to fetch vendors along with their countries and materials.
here is my details table, vendor_countries and vendor_materials tables
so far I made a query which is shown below:
select dt.vendor,
dt.email,
dt.address,
c.country,
m.material,
c.country
from country c
inner join vendor_countries vc on (c.id = vc.cid)
right join details dt on (dt.id = vc.did)
left join vendor_materials vm on dt.id = vm.did
left join material m on vm.mid = m.id
and i am getting results like this:
which is not right it should be in 3 rows because "ali" vendor works in 3 countries and 3 materials. I am looking for some smart solution which also not slow down my page. Thanks in advance.

In the absence of any response regarding table schema I tried to re-create the tables based upon the descriptions above -prefixing each table with v_ so I could group the tables in this db and referencing did as vid ( vendor id ) and populating with what I believed to be the sample data from the question
mysql> describe v_country;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+------------------+------+-----+---------+----------------+
mysql> describe v_details;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| vendor | varchar(50) | YES | | NULL | |
| email | varchar(50) | YES | | NULL | |
| phone | varchar(50) | YES | | NULL | |
| address | varchar(50) | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
mysql> describe v_materials;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+------------------+------+-----+---------+----------------+
mysql> describe v_vendor_materials;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| vid | int(10) unsigned | NO | MUL | 0 | |
| mid | int(10) unsigned | NO | MUL | 0 | |
+-------+------------------+------+-----+---------+----------------+
mysql> describe v_vendor_countries;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| vid | int(10) unsigned | NO | MUL | 0 | |
| mid | int(10) unsigned | NO | MUL | 0 | |
+-------+------------------+------+-----+---------+----------------+
mysql> select * from v_country;
+----+----------+
| id | name |
+----+----------+
| 1 | pakistan |
| 2 | India |
| 3 | Iran |
+----+----------+
mysql> select * from v_details;
+----+--------+------------------+---------------+-----------+
| id | vendor | email | phone | address |
+----+--------+------------------+---------------+-----------+
| 1 | harris | harris#gmail.com | 0141 236 4523 | nowhere |
| 2 | Boris | boris#gmail.com | 0141 451 7845 | somewhere |
| 3 | Doris | doris#gmail.com | 0141 353 7845 | anywhere |
+----+--------+------------------+---------------+-----------+
mysql> select * from v_materials;
+----+---------+
| id | name |
+----+---------+
| 1 | ceramic |
| 2 | iron |
| 3 | plastic |
+----+---------+
mysql> select * from v_vendor_materials;
+----+-----+-----+
| id | vid | mid |
+----+-----+-----+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
+----+-----+-----+
mysql> select * from v_vendor_countries;
+----+-----+-----+
| id | vid | mid |
+----+-----+-----+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
+----+-----+-----+
mysql> select * from v_details d
left outer join v_vendor_materials vm on vm.vid=d.id
left outer join v_vendor_countries vc on vc.vid=d.id
left outer join v_materials m on m.id=vm.id
left outer join v_country c on c.id=vc.id;
+----+--------+------------------+---------------+-----------+------+------+------+------+------+------+------+---------+------+----------+
| id | vendor | email | phone | address | id | vid | mid | id | vid | mid | id | name | id | name |
+----+--------+------------------+---------------+-----------+------+------+------+------+------+------+------+---------+------+----------+
| 1 | harris | harris#gmail.com | 0141 236 4523 | nowhere | 1 | 1 | 1 | 1 | 1 | 1 | 1 | ceramic | 1 | pakistan |
| 2 | Boris | boris#gmail.com | 0141 451 7845 | somewhere | 2 | 2 | 2 | 2 | 2 | 2 | 2 | iron | 2 | India |
| 3 | Doris | doris#gmail.com | 0141 353 7845 | anywhere | 3 | 3 | 3 | 3 | 3 | 3 | 3 | plastic | 3 | Iran |
+----+--------+------------------+---------------+-----------+------+------+------+------+------+------+------+---------+------+----------+
or, a more selective query
select
d.`id` as `vid`,
d.`vendor`,
d.`email`,
d.`phone`,
d.`address`,
m.`name` as `material`,
c.`name` as `country`
from v_details d
left outer join v_vendor_materials vm on vm.vid=d.id
left outer join v_vendor_countries vc on vc.vid=d.id
left outer join v_materials m on m.id=vm.id
left outer join v_country c on c.id=vc.id;
+-----+--------+------------------+---------------+-----------+----------+----------+
| vid | vendor | email | phone | address | material | country |
+-----+--------+------------------+---------------+-----------+----------+----------+
| 1 | harris | harris#gmail.com | 0141 236 4523 | nowhere | ceramic | pakistan |
| 2 | Boris | boris#gmail.com | 0141 451 7845 | somewhere | iron | India |
| 3 | Doris | doris#gmail.com | 0141 353 7845 | anywhere | plastic | Iran |
+-----+--------+------------------+---------------+-----------+----------+----------+

Related

SQL Union 1 Column within Larger Query with Laravel ORM?

I'm currently storing addresses for multiple different objects. So there is addresses for jobs, companies, etc.
I want to be able to get all addresses.* and a union of jobs.job_title & companies.company_name to select an object_name for each addresses record.
Address.php (Model)
static $object_type = [
1 => 'Company',
2 => 'Job',
];
static public function getObjectTypes() {
return self::$object_type;
}
static public function getObjectTypeName($key) {
return self::$object_type[$key];
}
static public function getAddresses(){
$addresses = Address::select(
'addresses.*'
)->where('addresses.soft_deleted', 0);
$addresses->limit(20);
return $addresses->get();
}
The current schema for addresses table:
+-------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+----------------+
| id | int(12) unsigned | NO | PRI | NULL | auto_increment |
| object_id | int(12) | YES | MUL | 0 | |
| object_type | tinyint(3) | YES | | 1 | |
| address | varchar(255) | YES | | NULL | |
| soft_deleted | tinyint(3) unsigned | YES | | 0 | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+-------------------+---------------------+------+-----+---------+----------------+
The current schema for jobs table:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | int(12) unsigned | NO | PRI | NULL | auto_increment |
| company_id | int(12) | YES | | 0 | |
| job_title | varchar(99) | YES | | NULL | |
| soft_deleted | tinyint(3) unsigned | YES | | 0 | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL |
+-----------------+---------------------+------+-----+---------+----------------+
The current schema for companies table:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | int(12) unsigned | NO | PRI | NULL | auto_increment |
| company_name | varchar(99) | YES | | NULL | |
| soft_deleted | tinyint(3) unsigned | YES | | 0 | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL |
+-----------------+---------------------+------+-----+---------+----------------+
My question is: How would I create the union and return the data needed based on the above structure?
Here is a SQLFiddle of what I think you are after. This is a very simplified schema to illustrate what is being done:
addresses
id | objectId | objectType | address
1 | 1 | 1 | 4657
2 | 1 | 3 | 3465
3 | 2 | 4 | 4536
4 | 1 | 2 | 3098
5 | 2 | 1 | 5647
6 | 2 | 2 | 8989
7 | 1 | 4 | 4563
8 | 2 | 3 | 2345
companies
id | name
1 | 'Acme Anvils'
2 | 'McBarfles'
3 | 'Noke'
4 | 'Stab Mart'
jobs
id | companyId | title
1 | 4 | 'Fly Swatter'
2 | 3 | 'Palm Greaser'
3 | 2 | 'McBarfle Burger Tender'
4 | 1 | 'Shill'
Assuming that objectType 1 = Company and objectType 2 = Job:
SELECT
'Company' AS objectType,
c.name,
a.address
FROM addresses a
INNER JOIN companies c
ON a.objectId = c.id
WHERE a.objectType = 1
UNION ALL
SELECT
'Job' AS objectType,
j.title,
a.address
FROM addresses a
INNER JOIN jobs j
ON a.objectId = j.id
WHERE a.objectType = 2
This breaks the joins up into sections based on the objectType in the addresses table, then UNION ALLs the results together to get the final list of addresses and object names:
objectType | name | address
Company | Acme Anvils | 4657
Company | Noke | 3465
Company | McBarfles | 3098
Company | Stab Mart | 4563
Job | Shill | 4536
Job | Fly Swatter | 5647
Job | Palm Greaser | 8989
Job | McBarfle Burger Tender | 2345
Note that you would have to manually add additional queries to be UNION ALLed for each possible value of objectType.

tag cloud with mysql

Is there any other way to make tag cloud from mysql without temporary tables?
mysql> explain wallpaper_keywords;
+--------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------------------+------+-----+---------+----------------+
| id | mediumint(7) unsigned | NO | PRI | NULL | auto_increment |
| wallpaper_id | mediumint(7) unsigned | YES | MUL | NULL | |
| keyword_id | smallint(5) unsigned | YES | MUL | NULL | |
+--------------+-----------------------+------+-----+---------+----------------+
mysql> explain keywords;
+---------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------------------+------+-----+---------+----------------+
| id | mediumint(7) unsigned | NO | PRI | NULL | auto_increment |
| keyword | varchar(32) | YES | UNI | NULL | |
+---------+-----------------------+------+-----+---------+----------------+
SELECT k.keyword,count(k.keyword) AS count FROM keywords k Left Join wallpaper_keywords wk ON wk.keyword_id = k.id GROUP BY wk.keyword_id, k.keyword ORDER BY count DESC limit 100;
+----------+-------+
| keyword | count |
+----------+-------+
| computer | 10 |
| road | 4 |
| tree | 4 |
| window | 4 |
| nature | 4 |
| forest | 3 |
| cars | 3 |
| mazda | 3 |
| abstract | 3 |
| funny | 3 |
| sport | 3 |
| sea | 3 |
| city | 3 |
| warrior | 2 |
| bird | 2 |
| lights | 1 |
| summer | 1 |
| space | 1 |
| dusk | 1 |
| ubuntu | 1 |
+----------+-------+
explain:
+----+-------------+--------------------+-------+---------------+---------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------------+-------+---------------+---------+---------+------+------+----------------------------------------------+
| 1 | PRIMARY | keywords | index | NULL | keyword | 99 | NULL | 20 | Using index; Using temporary; Using filesort |
| 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 54 | |
| 2 | DERIVED | wallpaper_keywords | index | NULL | PRIMARY | 3 | NULL | 54 | |
+----+-------------+--------------------+-------+---------------+---------+---------+------+------+----------------------------------------------+
3 rows in set (0.00 sec)
EDIT
another query:
SELECT count,k.keyword from (SELECT * , count(wk.keyword_id) AS count FROM wallpaper_keywords wk GROUP BY wk.keyword_id LIMIT 50000) as data left join keywords as k on k.id = data.keyword_id order by count desc limit 500
+----+-------------+------------+--------+---------------+------------+---------+-----------------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+---------------+------------+---------+-----------------+------+----------------+
| 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 20 | Using filesort |
| 1 | PRIMARY | k | eq_ref | PRIMARY | PRIMARY | 3 | data.keyword_id | 1 | |
| 2 | DERIVED | wk | index | NULL | keyword_id | 3 | NULL | 59 | |
+----+-------------+------------+--------+---------------+------------+---------+-----------------+------+----------------+
the question would be now - is there any better solution? cheaper (SHOW STATUS LIKE 'last_query_cost';) way to count it?
For counting total value for every keyword you cau use additional field (total_count) in table keywords and by every adding new keyword add +1 to this field - it's really simpler for your database in future, when you will have 100 000 records.

mysql query takes 145 seconds

I have a a mysql db with myisam engine. Along with many other table I have this table "et" which has around 8137037 records.
I have created indexes (individual index of column hname and pnum, it did not help much later created joint index of hname and pnum and it help execute within a second)such that queries as follows
select st from et where hname='name' and pnum='1' limit 1
execute fast (with in a second) but the problem is I must execute this query
select st from et where hname='name' and pnum='1' order by id limit 1
where id is the primary key of the table and this query sometimes take 145 seconds :(
how can i resolve this issue?
table structure
mysql> describe et;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| client_id | int(11) | YES | MUL | NULL | |
| down_id | bigint(20) | YES | MUL | NULL | |
| port_index | int(11) | YES | | NULL | |
| date1 | bigint(20) | YES | MUL | NULL | |
| username | varchar(50) | YES | | NULL | |
| hname | varchar(80) | YES | MUL | NULL | |
| pnum | varchar(10) | YES | MUL | NULL | |
| status | int(3) | YES | MUL | NULL | |
| department | int(2) | YES | MUL | NULL | |
| comments | text | YES | | NULL | |
| issue | int(1) | YES | MUL | NULL | |
+------------+-------------+------+-----+---------+----------------+
12 rows in set (0.06 sec)
Indexes
mysql> show indexes from et;
+-----+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
|Table| Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-----+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| et | 0 | PRIMARY | 1 | id | A | 8137037 | NULL | NULL | | BTREE | |
| et | 1 | status | 1 | status | A | 12 | NULL | NULL | YES | BTREE | |
| et | 1 | down_id | 1 | down_id | A | 4068518 | NULL | NULL | YES | BTREE | |
| et | 1 | issue_idx | 1 | issue | A | 8137037 | NULL | NULL | YES | BTREE | |
| et | 1 | hname_idx | 1 | hname | A | 283 | NULL | NULL | YES | BTREE | |
| et | 1 | pname_idx | 1 | pnum | A | 136 | NULL | NULL | YES | BTREE | |
| et | 1 | clientid_idx | 1 | client_id | A | 8137037 | NULL | NULL | YES | BTREE | |
| et | 1 | date1_idx | 1 | date1 | A | 8137037 | NULL | NULL | YES | BTREE | |
| et | 1 | department_idx | 1 | department | A | 2712345 | NULL | NULL | YES | BTREE | |
| et | 1 | hp_idx | 1 | hname | A | 283 | NULL | NULL | YES | BTREE | |
| et | 1 | hp_idx | 2 | pnum | A | 4834 | NULL | NULL | YES | BTREE | |
+-----+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
11 rows in set (0.06 sec)
Explain Plan
mysql> explain select status from et where hname='mmah' and port_num='1' limit 1;
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-------------+
| 1 | SIMPLE | error_trap | ref | hname_idx,pname_idx,hostport_idx | hostport_idx | 96 | const,const | 37 | Using where |
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-------------+
1 row in set (0.02 sec)
mysql> explain select status from et where host_name='mmah' and pnum='1' order by id desc limit 1;
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-----------------------------+
| 1 | SIMPLE | error_trap | ref | hname_idx,pname_idx,hostport_idx | hostport_idx | 96 | const,const | 37 | Using where; Using filesort |
+----+-------------+------------+------+----------------------------------+--------------+---------+-------------+------+-----------------------------+
1 row in set (0.00 sec)
Have you tried creating an index of (id, hname,pnum)?
If your index includes and is already ordered by ID then that effectively removes that concern.
There is no reason you cannot include ID in another index, just because it is also the primary.
Create an index in the table that contains hname and pnum.
This will cause MYSQL to create a shadow table, which only contains those 2 parameters, and whenever those 2 parmaters are used in a where, it looks in that shadow table, and finds them very fast.

Number of games a particular user has played today where there is no data

I'm trying to get the number of games that summoners in the queue have played today. I have tried several queries. The closest I have gotten is:
SELECT
s.summoner,
s.wins,
COUNT(*) as playedToday
FROM summoners s
LEFT JOIN teams_players tp ON tp.summoner_id = s.summoner
LEFT JOIN teams t ON t.id = tp.team_id
LEFT JOIN matches b ON t.id = b.blue_id
WHERE
b.played_on = DATE(NOW())
s.in_queue;
But that doesn't give the count per-user. It just gets the overall count.
None of the tables have any data on any of the summoners. What I'd like is something like:
+-----------------+------+-------------+
| summoner | wins | gamesPlayed |
+-----------------+------+-------------+
| DotAliscious | 353 | 0 |
| Kraator | 440 | 0 |
| Nammon | 667 | 0 |
| VictorousSecret | 843 | 0 |
| Canas | 544 | 0 |
| Sprognak | 502 | 0 |
| Ghostilocks | 808 | 0 |
| b0b d0e | 224 | 0 |
| Metroshica | 339 | 0 |
| RubenatorX | 478 | 0 |
+-----------------+------+-------------+
I can't think how to express this problem generically, which is why I haven't found a solution.
My data set. Note that teams.id matches up with matches.blue_id and matches.purple_id.
mysql> DESCRIBE summoners;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| icon | int(11) | NO | | 0 | |
| summoner | varchar(32) | NO | UNI | NULL | |
| skype | varchar(32) | NO | | NULL | |
| email | varchar(32) | NO | | NULL | |
| in_queue | tinyint(1) | NO | | 0 | |
| wins | int(11) | NO | | 0 | |
| level | int(11) | NO | | 1 | |
| lan_wins | int(11) | NO | | 0 | |
| played_today | int(11) | NO | | 0 | |
+--------------+-------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)
mysql> DESCRIBE matches;
+-----------+-------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| blue_id | int(11) | NO | MUL | NULL | |
| purple_id | int(11) | NO | MUL | NULL | |
| status | varchar(32) | NO | | display | |
| played_on | datetime | NO | | 2012-04-06 13:53:55 | |
+-----------+-------------+------+-----+---------------------+----------------+
5 rows in set (0.00 sec)
mysql> DESCRIBE teams;
+---------+-------------+------+-----+------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| outcome | varchar(32) | NO | | incomplete | |
+---------+-------------+------+-----+------------+----------------+
2 rows in set (0.00 sec)
mysql> DESCRIBE teams_players;
+-------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| team_id | int(11) | NO | MUL | NULL | |
| summoner_id | int(11) | NO | MUL | NULL | |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
You're going to want to use a subselect to get the count of records that meet the condition, and that will return you a 0 if the condition is false. Something along the lines of
(SELECT COUNT(*) FROM matches b WHERE b.blue_id = t.id AND b.played_on = DATE(NOW())) AS playedToday
and you will want to remove the LEFT JOIN to the matches table and the WHERE clause checking the date.
Your played_on is datetime and you are comparing it with date maybe that's your problem. YOu should try:
WHERE
DATE(b.played_on) = DATE(NOW())
Also what do you mean by s.in_queue? Did you forget the AND? Do you mean
WHERE
DATE(b.played_on) = DATE(NOW())
AND
s.in_queue;

SQL Query using MySQL sample employee database

I have a problem making an advanced (for me) query.
I am trying to get the first name, last name, title, department name, and first and last name of the manager. I am using this SQL in PHP if for some reason you needed to know. I limit to 10 because the database is enormous. I need only the entry for the employees latest data. They have more than one entry because of job promotions, etc.
I included everything I think you would need to understand my problem. Thanks if you can help.
mysql>
SELECT DISTINCT employees.first_name, employees.last_name,
titles.title, departments.dept_name, z.first, z.last
FROM employees, dept_emp, departments, titles,
(
SELECT employees.first_name AS first, employees.last_name AS last
FROM employees, dept_emp, dept_manager
WHERE
employees.emp_no = dept_emp.emp_no
AND dept_manager.emp_no = dept_emp.emp_no
) AS z
WHERE
employees.emp_no = dept_emp.emp_no
AND dept_emp.dept_no = departments.dept_no
AND titles.emp_no = employees.emp_no
LIMIT 10;
+------------+-----------+-----------------+-------------+-----------+--------------+
| first_name | last_name | title | dept_name | first | last |
+------------+-----------+-----------------+-------------+-----------+--------------+
| Georgi | Facello | Senior Engineer | Development | Margareta | Markovitch |
| Georgi | Facello | Senior Engineer | Development | Vishwani | Minakawa |
| Georgi | Facello | Senior Engineer | Development | Ebru | Alpin |
| Georgi | Facello | Senior Engineer | Development | Isamu | Legleitner |
| Georgi | Facello | Senior Engineer | Development | Shirish | Ossenbruggen |
| Georgi | Facello | Senior Engineer | Development | Karsten | Sigstam |
| Georgi | Facello | Senior Engineer | Development | Krassimir | Wegerle |
| Georgi | Facello | Senior Engineer | Development | Rosine | Cools |
| Georgi | Facello | Senior Engineer | Development | Shem | Kieras |
| Georgi | Facello | Senior Engineer | Development | Oscar | Ghazalie |
+------------+-----------+-----------------+-------------+-----------+--------------+
10 rows in set (0.00 sec)
The database is the employees database from mysql.com:
http://dev.mysql.com/doc/index-other.html
mysql> desc departments;
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| dept_no | char(4) | NO | PRI | NULL | |
| dept_name | varchar(40) | NO | UNI | NULL | |
+-----------+-------------+------+-----+---------+-------+
2 rows in set (0.22 sec)
mysql> desc dept_emp;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| dept_no | char(4) | NO | PRI | NULL | |
| from_date | date | NO | | NULL | |
| to_date | date | NO | | NULL | |
+-----------+---------+------+-----+---------+-------+
4 rows in set (0.20 sec)
mysql> desc dept_manager;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| dept_no | char(4) | NO | PRI | NULL | |
| emp_no | int(11) | NO | PRI | NULL | |
| from_date | date | NO | | NULL | |
| to_date | date | NO | | NULL | |
+-----------+---------+------+-----+---------+-------+
4 rows in set (0.21 sec)
mysql> desc employees;
+------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| birth_date | date | NO | | NULL | |
| first_name | varchar(14) | NO | | NULL | |
| last_name | varchar(16) | NO | | NULL | |
| gender | enum('M','F') | NO | | NULL | |
| hire_date | date | NO | | NULL | |
+------------+---------------+------+-----+---------+-------+
6 rows in set (0.32 sec)
mysql> desc salaries;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| salary | int(11) | NO | | NULL | |
| from_date | date | NO | PRI | NULL | |
| to_date | date | NO | | NULL | |
+-----------+---------+------+-----+---------+-------+
4 rows in set (0.34 sec)
mysql> desc titles;
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| title | varchar(50) | NO | PRI | NULL | |
| from_date | date | NO | PRI | NULL | |
| to_date | date | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.60 sec)
I am trying to get the first name, last name, title, department name, and first and last name of the manager
Using the theory (but it's probably not optimized if you have large tables), do it step by step. Assuming you have a $date PHP variable that contains a date (like the result from date('Y-m-d 00:00:00')), or otherwise you may use MySQL's date.
1/ get employees' identity:
SELECT
e.first_name,
e.last_name
FROM
employees AS e
WHERE
1
2/ add his/her current title
SELECT
e.first_name,
e.last_name,
t.title
FROM
employees AS e,
titles AS t
WHERE
e.emp_no=t.emp_no AND t.from_date<='$date' AND t.to_date>='$date'
3/ get his/her current department (from dept_emp) and retrieve the department's name
SELECT
e.first_name,
e.last_name, t.title,
d.dept_name
FROM
employees AS e,
titles AS t,
dept_emp AS de,
departments as d
WHERE
e.emp_no=t.emp_no AND t.from_date<='$date' AND t.to_date>='$date'
AND
e.emp_no=de.emp_no AND de.from_date<='$date' AND de.to_date>='$date'
AND
d.dept_no=de.dept_no
4/ get the department's manager (from dept_manager) and retrieve his/her name (from employees)
SELECT
e.first_name AS empFN,
e.last_name AS empLN,
t.title AS empT,
d.dept_name AS dept,
em.first_name AS manFN,
em.last_name AS manLN
FROM
employees AS e,
titles AS t,
dept_emp AS de,
departments as d,
dept_manager AS dm,
employees AS em
WHERE
e.emp_no=t.emp_no AND t.from_date<='$date' AND t.to_date>='$date'
AND
e.emp_no=de.emp_no AND de.from_date<='$date' AND de.to_date>='$date'
AND
d.dept_no=de.dept_no
AND
em.emp_no=dm.emp_no AND dm.from_date<='$date' AND dm.to_date>='$date'
AND
de.dept_no=dm.dept_no
There you can append a LIMIT (and an ORDER BY probably, you don't know which results will be picked in case of a limit), and/or add in the WHERE an emp_no for the employee(s) you want to have info about. Not tested though, but it's mainly to let you understand how to build the request.
This is theory, and this request is probably be as heavy to process as the one you wrote. Since you use SQL with PHP, it may be better to retrieve only the primary keys you're interested in, then send short requests to retrieve the information you want. Something like that I mean (using fake functions but the spirit's here):
$dateString="from_date<='$date' AND to_date>='$date'";
$qe=query("SELECT emp_no, first_name, last_name, dept_no FROM employees, dept_emp WHERE dept_emp.emp_no=employees.emp_no LIMIT 10 ORDER BY emp_no DESC");
while($r=fetch($qe)) {
$qt=fetch(query("SELECT title FROM titles WHERE emp_no=".$qe['emp_no']." AND ".$dateString));
$qd=fetch(query("SELECT dept_name FROM departments WHERE dept_no=".$qe['dept_no']." AND ".$dateString));
$qm=fetch(query("SELECT first_name, last_name FROM employees AS e, dept_manager AS dm WHERE dept_no=".$qe['dept_no']." AND e.emp_no=dm.emp_no AND ".$dateString));
//echo/process here
}
Hope this helps :)

Categories