我可以根据多个其他表从表中获取数据吗?

时间:2015-12-08 05:57:38

标签: php mysql sql database mysqli

$query = "SELECT * FROM table3 WHERE name_id = '(SELECT name_id FROM table2
WHERE salary < 1000 && name = '(SELECT name FROM table1
WHERE savings > 1000)')'";

基本上我想基于节省从table1获取数据,并使用它从表2中获取数据并使用该数据从表3中获取所有信息。但这不会起作用。我的代码是对的还是我做错了什么?

我也无法创建新表,我只想显示表3中的数据。

4 个答案:

答案 0 :(得分:2)

使用join

SELECT * FROM table3 t3 join table2 t2 
on t3.name_id=t2.name_id
join table1 t1
on t3.name=t1.name
where salary < 1000 and savings > 1000

答案 1 :(得分:1)

$query="SELECT * FROM table3 LEFT JOIN table2 ON    table3.name_id=table2.name_id
LEFT JOIN table1 ON table3.name=table1.name 
WHERE table2.salary < 1000  AND table1.savings > 1000 "

答案 2 :(得分:0)

另一种连接语法是

SELECT * FROM table1 t1,table2 t2 ,table3 t3 
where t1.name = t3.name and 
t2.name_id = t3.name_id and 
t1.savings > 1000 and t2.salary < 1000;

答案 3 :(得分:0)

$query = "SELECT t3.* FROM table3 t3 
INNER JOIN table2 t2 ON t2.name_id = t3.name_id AND t2.salary < 1000
INNER JOIN table1 t1 ON t1.name = t2.name AND t1.savings > 1000";