2014-03-04 112 views
-1

我有3个表。 3个表有一个名为“hobbyid”的字段,我需要在sql查询中加入3。PHP SQL查询通过一个字段加入3个表

我现在所拥有的是一个表:

$result = mysqli_query($con,"SELECT * FROM table1 WHERE username='".$username."' "); 

下面是相同的样本结构:

table1 

+----+----------+----------+---------+ 
| id | username | password | hobbyid | 
+----+----------+----------+---------+ 

table2 

+----+----------+---------------+---------+ 
| id | username | somethingelse | hobbyid | 
+----+----------+---------------+---------+ 

table3 

+----+----------+-----------+---------+ 
| id | username | something | hobbyid | 
+----+----------+-----------+---------+ 

我怎样才能加入3个表,所以我可以从所有3得到的数据?

+0

你期待什么?具有不同名称的字段应该如何合并? –

+0

我需要能够访问3个表上的所有字段,方法是使用3个表中存在的hobbyid字段加入它们 – Satch3000

回答

1

即使实际上没有必要创建3个表,但还是如果你觉得它是必需的,那么你可以使用UNION ALL(如果你需要所有重复的值也)或者工会,如果你需要不同的价值。但为此,所有表中应该有相同的列。

下面的查询使用,如果你需要从所有3个表 -

select * from table1 where username='abc' 
union all 
select * from table2 where username='abc' 
union all 
select * from table3 where username='abc'; 

的所有数据。如果您要根据hobbyid唯一共同的数据,然后使用下面的query

select a.username,a.password,a.hobbyid,b.somethingelse,c.something from table1 a join table2 b on a.hobbyid=b.hobbyid join table 3 c on a.hobbyid=c.hobbyid where a.username='abc'; 

如果这两个不适合对你来说,请详细说明你的要求。

+0

我认为在使用联合时,表格需要有相同的列:? –

+0

不是同一列,但列数相同......在这种情况下,somethingelse将进入密码列...您可以说它不实用,但可能适用于处于特殊状况的人。 –

1

这是否有诀窍?

$result = mysqli_query($con,"SELECT id, username, hobbyid FROM table1 WHERE username='".$username."' 
UNION ALL (SELECT id, username, hobbyid FROM table2 WHERE username='".$username."') 
UNION ALL (SELECT id, username, hobbyid FROM table3 WHERE username='".$username."')"); 

这将只能加入ID,用户名,hobbyid - 所有其他字段将被中省略。如果你想坚持他们,你将不得不使用JOIN-s。

+0

我可能需要连接,因为我也需要访问其他字段,我只需要验证用户名就可以表格1。 – Satch3000

1
select * from table1 a, table2 b, table3 c 
where a.username= '$username' and b.username= '$username' and c.username='$username' 
//(or) 

//if you want to get the data having same username from tabls 
select * from table1 a 
inner join table2 b on a.username= b.username 
inner join course c on b.username= c.username