在查询方面需要一些帮助。我在数据库、联系人和任务中有 2 个表。
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 | |
+-------------------+--------------+------+-----+---------+----------------+
我想从任务表中获取信息,但我想用匹配的contact_id 中的一些字段替换contact_id1-contact_id6。我一直在搞乱嵌套的选择语句,这些语句可以工作但非常混乱。似乎必须有一种更清洁的方法来做到这一点。我以为我有这个,
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
但我在这里的问题是,它没有显示任何 contact_id1-contact_id6 的值的值为 0 的任务,如果没有为它设置 contact_id,这是默认值。
你能提供的任何帮助都会很棒。