如何在mysql中加入两个表并使用php显示它?

时间:2012-12-07 14:39:33

标签: php mysql

我有两张桌子。结构是:

mysql> desc working;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| worker_id   | varchar(12) | YES  |     | NULL    |       | 
| worker_duty | varchar(30) | YES  |     | NULL    |       | 
| salary      | varchar(8)  | YES  |     | NULL    |       | 
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> desc users;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| user_id     | varchar(12)  | YES  |     | NULL    |       | 
| user_name   | varchar(21)  | YES  |     | NULL    |       | 
| discription | varchar(200) | YES  |     | NULL    |       | 
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

我想使用worker_iduser_id加入这两个表,并使用PHP获取它。

我用:

SELECT * from users t1
WHERE user_id="293274"
AND SELECT worker_duty ,worker_id from working t2
             WHERE t1.user_id= t2.worker_id

但是这段代码不起作用。

4 个答案:

答案 0 :(得分:2)

内部联接

select u.user_id, u.user_name, u.discription, w.worker_duty
from users u
inner join working w on w.worker_id = u.user_id
where u.user_id = "293274";

答案 1 :(得分:0)

也许是这样的?

 'SELECT u.user_id, u.user_name, u.discription, w.worker_duty FROM users as u
 JOIN working as w ON u.user_id=w.worker_id
 WHERE w.user_id="293274"

答案 2 :(得分:0)

SELECT users.user_id, users.user_name, user.discription, working.working_duty FROM user JOIN working ON user.user_id = working.worker_id WHERE user.user_id="293274"

答案 3 :(得分:0)

使用如下连接:

     SELECT t1.*,  t2.worker_duty , t2.worker_id  
     from users t1 JOIN working t2
          ON t1.user_id= t2.worker_id 
     WHERE t1.user_id="293274"