美好的一天! 我不熟悉PHP和MySQL的多个查询,我没有找到我的问题的答案(也许这是不可能的?)。 我有一个包含多个表的数据库,我尝试构建一个多重查询(在PHP中),它依赖于前一个查询的结果。以下是我的数据库示例:
Table1
id:1, first_name: Sally, last_name:Meyers,
id:2, first_name: George, last_name:Smith,
id:3, first_name: Peter, last_name:Gabriel,
id:4, first_name: John, last_name:Doe
Table2
type: hystory, number: 123456789, last_name:Meyers,
type: suspense, number: 1321465447, last_name: Smith,
type: sci-fi, number: 931213246, last_name: Gabriel,
type: suspense, number: 555221321, last_name: Doe
Table3
title: War and Peace, year: 1997, author: 3, type: hystory,
title: Justice for all!, year: 2014, author: 1, type: suspense,
title: Time lost, year: 2001, author: 2, type: sci-fi,
title: The cold war, year: 1981, author: 3, type: suspense,
我的查询是这样的:
SELECT first_name, last_name FROM Table1 WHERE id=3 AND SELECT sci-fi FROM Table2 WHERE last_name = [result of the first query] AND SELECT title FROM Table3 WHERE type = [result of the second query];
最后,我要做的就是将(通过AJAX)单个JSON对象返回到由数据库中所选元素组成的Javascript。 你能帮忙构建这个多重查询吗?
答案 0 :(得分:1)
你可能需要加入3表,例如:
SELECT first_name
, last_name
FROM Table1
INNER JOIN Table2 ON Table2.last_name = Table1.last_name
INNER JOIN Table3 ON Table3.type = Table2.type
WHERE Table1.id=3
答案 1 :(得分:0)
SELECT foo.first_name, foo.last_name, bar.title
FROM table1 as foo
JOIN table2 as bar on foo.last_name = bar.last_name
JOIN table3 as cat on bar.type = cat.type
WHERE foo.id=3 and bar.type="sci-fi"
我认为:)
答案 2 :(得分:0)
您可以使用JSON转换...
SELECT json_object('FirstName', t1.first_name, 'LastName', t1.last_name,'Sci-Fi', t2.sci-fi, 'Title',t3.title)
FROM Table1 t1
join Table t2
on t1.last_name = t2.last_Name
join Table t3
on t2.type = t3.type
WHERE t1.id=3