从多个表中选择多个行

时间:2017-07-31 07:27:25

标签: php mysql

表1

 id  | name | can  | some
---- +------+------+-----
1    |A     | can1 | f
2    |B     | can0 | g
3    |C     | can1 | h
4    |d     | can2 | i

表2

id  | name | description
----+------+--------------
1   |can0  | some text
2   |can1  | another text
3   |can2  | text to

我有两张桌子。我希望从id=3获取 table1行,并从description获取can1 table2

我试过这个

SELECT t1.* , t2.description 
from table1 as t1 , table2 as t2 
WHERE t1.can = t2.name

但这不起作用。请帮助谢谢

6 个答案:

答案 0 :(得分:1)

维护第二个表的ID而不是文本

表: - T1

id  | name | can    | can_id
---- +------+-------+--------
1    |A     | can1  |  2
2    |B     | can0  |  1
3    |C     | can1  |  2

表: - T2

id  | name | description
----+------+--------------
1   |can0  | some text
2   |can1  | another text
3   |can2  | text to

查询没有维护ID O表T2

select t1.*,t2.* from T1 as t1 join T2 as t2 on t1.can = t2.name

使用Id

select  t1.*,t2.* from T1 as t1 join T2 as t2 on t1.can_id = t2.id

答案 1 :(得分:0)

SELECT table1 .*, table2.description 
from table1
JOIN table2 on table1.can = table2.name
where table1.id =3

最好的方法是连接两个表,并使用连接表中所需的列(在本例中为table2.description)

答案 2 :(得分:0)

您忘记将t1.id = 3放入WHERE条款。

SELECT t1.* , t2.description 
from table1 as t1 , table2 as t2 
WHERE t1.can = t2.name AND t1.id = 3

但是,您应该更加现代化并使用ANSI JOIN语法而不是交叉产品,如Zeljka的答案。

答案 3 :(得分:0)

试试这个...

SELECT t1.*, t2.* 
FROM table1 t1
JOIN table2 t2 ON t1.can = t2.name

答案 4 :(得分:0)

了解join

SELECT t1.*,t2.description  FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id where t1.id = 3

答案 5 :(得分:0)

您可以使用内部加入(如

)执行此操作
SELECT table1 .*, table2.description 
from table1
JOIN table2 on table1.can = table2.name
where table1.id =3

如果Table2是可选的,则使用左连接表示如果您没有相同的table1.cantable2.name,那么您将获得table1的所有值然后,
这样做:

SELECT table1 .*, table2.description 
from table1
LEFT JOIN table2 on table1.can = table2.name
where table1.id =3