![](/img/trans.png)
[英]mysql update rows of column in second table from column in first table where another column in first table matches column in second table
[英]MySQL fetch data from another table where the column row matches a row result from first table
我有2个表,可以说它们包含:
表格1
id | username
1 | Bla
4 | Bla2
表2
FROM_ID | FK_TOID | Action
1 | 2 | -1
4 | 2 | -1
现在我所拥有的就像:
SELECT FK_FROMID FROM table2 WHERE FK_TOID = 2 AND FP_ACTION = -1
我想做的是从表1中获取ID和用户名,其中表1的ID与表2中的FROM_ID匹配,其中表2中FK_TOID为'2'。
所以基本上返回的结果应该是这样的
[{ id: 1, FK_FROMID: 1, username: Bla }, { id: 4, FK_FROMID: 4, username: Bla2 }]
你需要这个:
SELECT A.id,B.from_id as FK_FROMID,A.username
FROM t1 A
LEFT JOIN t2 B
ON A.id=B.from_id
单击此链接以查看结果:
http://sqlfiddle.com/#!2/868c1/4
更新:1
SELECT A.id,B.from_id as FK_FROMID,A.username
FROM t1 A
LEFT JOIN t2 B
ON A.id=B.from_id
WHERE B.fk_toid=2 AND B.action=-1;
检查此链接:
您应按以下方式使用内部联接或左侧外部联接(与您的示例无关):
select t1.id, t2.FK_FROMID, t1.username
from Table1 t1
join Table2 t2
on (t2.FROM_ID = t1.id)
where t2.FK_VOID = 2
and t2.FP_ACTION = -1
尝试这个:
SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.from_id
where table2.TOID = '2'
您确实不需要为此使用任何联接。 一个简单的查询将如下工作:
select t1.id, t2.FK_FROMID, t1.username
from Table1 t1, Table2 t2
where t1.id = t2.FK_FROMID
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.