Php 查询mysql类似表的最佳方法是什么
我有三张桌子表一、表二、表三Php 查询mysql类似表的最佳方法是什么,php,mysql,Php,Mysql,我有三张桌子表一、表二、表三 Table1 user ID,name, class, rollno, maths, English, literature Table2 User ID, name, class, rollno, maths, English, physics Table3 User ID, name, class, rollno, maths, English, geography 查询mysql以获取一个不同结果的最佳方法是什么 $query = "select * fr
Table1
user ID,name, class, rollno, maths, English, literature
Table2
User ID, name, class, rollno, maths, English, physics
Table3
User ID, name, class, rollno, maths, English, geography
查询mysql以获取一个不同结果的最佳方法是什么
$query = "select * from table1 where class='class and rollno='rollno'
Union
select * from table2 where class='class and rollno='rollno'
Union
select * from table3 where class='class and rollno='rollno' ";
当我这样做时,它不起作用从您的问题很难理解您想要如何构建结果集,但一般来说,在sql中组合结果有两种主要方法:join和union
join
意味着获取两个数据集,并以一种方式连接它们,即结果中的每一行将包含来自这两个数据集的列,并且结果将通过某个共享列连接。在您描述的表结构中,可以使用userId来组合结果,从而为您提供一行userId、geography(来自表1)和physics(来自表2)
union
意味着获取两个数据集,并以一种方式连接它们,即每一行来自其中一个表,结果就是表1中的所有行+表2中的所有行(有或没有重复项)。这里的限制是两个数据集应该包含相同的列。例如,在您的表中,它可以从所有三个表中获取userId、name和math。正如我从您的问题中所理解的,您需要从三个或更多具有类似列名的表中获取所有不同的行 最好的方法是使用union,就像您正在做的那样,但在union中还需要指定列名
$query = "select User_ID, name, class, rollno, maths, English, physics from table1 where class='class and rollno='rollno'
Union
select User_ID, name, class, rollno, maths, English, physics from table2 where class='class and rollno='rollno'
Union
select User_ID, name, class, rollno, maths, English, physics from table3 where class='class and rollno='rollno' ";
这会帮你的。如果您需要包含重复条目的所有列,请使用union all您的问题缺少大量信息,请阅读。。假设你是我们中的一员,你第一次看到了答案:这有意义吗?试着自己在一个新的环境中重现这个问题,并确保你可以只使用问题中包含的信息,然后你会发现回答这个问题是多么不可能。。由于SQL是声明式的,您可以定义您想要的内容,而不是如何获取它,因此它并不容易。。。请看“最佳”方法是修复设计并避免“相似”表。是的,这是表不同的最佳方法,因此当我使用mysql Union时,我会得到一个mysqli_num_rows错误