Need some help with a query. I have 2 tables in a database, contacts & tasks.
mysql> describe contacts;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| contact_id | int(11) | NO | PRI | NULL | auto_increment |
| last_name | varchar(100) | YES | | NULL | |
| first_name | varchar(100) | YES | | NULL | |
| email | varchar(50) | YES | | NULL | |
| phone | varchar(20) | YES | | NULL | |
| school_id | varchar(12) | NO | | NULL | |
| access | char(1) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> describe tasks;
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| task_id | int(11) | NO | PRI | NULL | auto_increment |
| task_name | varchar(125) | YES | | NULL | |
| task_date | date | YES | | NULL | |
| task_description | text | YES | | NULL | |
| contact_id1 | int(11) | YES | | NULL | |
| contact_id2 | int(11) | YES | | NULL | |
| contact_id3 | int(11) | YES | | NULL | |
| contact_id4 | int(11) | YES | | NULL | |
| contact_id5 | int(11) | YES | | NULL | |
| contact_id6 | int(11) | YES | | NULL | |
| completed | char(1) | YES | | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
I want to get the info from the tasks table but I want to replace the contact_id1-contact_id6 with some of the fields from the matching contact_id. I have been messing around with nested select statements which will work but is very messy. It just seems there has to be a cleaner way to do this. I thought I had some with this,
SELECT tasks.task_id, tasks.task_name, tasks.reminder_time, tasks.reminder_interval, CONCAT (contact_1.first_name, " ", contact_1.last_name) as contact_1_name, CONCAT(contact_2.first_name, contact_2.last_name) as contact_2_name, CONCAT(contact_3.first_name, contact_3.last_name) as contact_3_name
FROM tasks
JOIN contacts contact_1 ON tasks.contact_id1 = contact_1.contact_id
JOIN contacts contact_2 ON tasks.contact_id2 = contact_2.contact_id
JOIN contacts contact_3 ON tasks.contact_id3 = contact_3.contact_id
But my issue here is that it is not showing tasks where any of the values of contact_id1-contact_id6 have a value of 0 which is the default value if no contact_id is set for it.
Any help you can provide would be great.
You can make a view that does normalize the tasks table then the join will be easy. You can make a permanent view or just for the select.
The view would need somehow to be a UNION
So then it looks like this
Have not tested this, but should work like this.
Edit: Actually was thinking about it. UNION ALL, at least for the temporary view is not necessary. Probably will bring you some time improvement if your tables are real large.