我有三個表用於存儲一些用戶數據。Mysql - 三表查詢
sub_domains
(經驗子域去這裏。exp_id
比賽id
在exp
和domain_id
比賽id
在misc
。所以user_id
和exp_id
可重複的,如果一個用戶擁有多個子域)
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(50) | YES | | NULL | |
| domain_id | int(10) | NO | | NULL | |
| exp_id | int(50) | YES | | NULL | |
+-----------+---------+------+-----+---------+----------------+
misc
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | YES | | NULL | |
| category | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
exp
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | | NULL | |
| job_type | varchar(60) | YES | | NULL | |
| experience | varchar(500) | YES | | NULL | |
| exp_title | varchar(255) | YES | | NULL | |
| domain | varchar(125) | YES | | NULL | |
| start | varchar(20) | YES | | NULL | |
| end | varchar(20) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
這是查詢我有個大氣壓,從EXP抓取數據:
$query_str = "SELECT a.id, a.user_id, a.job_type, a.experience, a.exp_title, a.domain, a.start, a.end, b.name
FROM exp a
JOIN misc b ON a.domain=b.id
WHERE a.user_id = ?";
我已經從misc
獲取域名,但我也想從misc
每個子域的名稱也是,但我不知道如何改變查詢。
編輯
我曾在這一點,本想出了:
$query_str = "SELECT a.id, a.user_id, a.job_type, a.experience, a.exp_title, a.domain, a.start, a.end, b.name,
(SELECT GROUP_CONCAT(domain_id) FROM sub_domains sd WHERE a.id=sd.exp_id) AS subs,
(SELECT GROUP_CONCAT(name) FROM misc WHERE id IN(subs)) AS subcats
FROM exp a
JOIN misc b ON a.domain=b.id
WHERE a.user_id = ?";
它幾乎工程,subcats的的var_dump只返回misc
表中的第一name
。
不......它只是返回4或5每個經驗。 – Ciprian 2012-07-24 14:32:37
如果您想要表a中的所有記錄,則嘗試使用LEFT JOIN而不是INNER JOIN。 – Omesh 2012-07-25 07:57:58