简体   繁体   English

我应该使用UNION还是其他方式从多个表中选择数据?

[英]Should I use UNION or something else for selecting data from multiple tables?

I have two tables in my mysql database: female and male . 我的mysql数据库中有两个表: femalemale They both have 3 columns each: id , name and age . 它们都有3列: idnameage I want a html table to be displayed with both table's data in it. 我希望显示一个HTML表,其中包含两个表的数据。

I have these code pieces: 我有以下代码段:

$result = mysql_query("SELECT * FROM female ORDER BY age DESC LIMIT 20");
while($row = mysql_fetch_array($result))
{
  $age = $row['age'];
  $name = $row['name'];
}

and

$result01 = mysql_query("SELECT * FROM male ORDER BY age DESC LIMIT 20");
while($row01 = mysql_fetch_array($result01))
{
  $age01 = $row01['age'];
  $name01 = $row01['name'];
}

So how should I mix these tables (the data)? 那么我应该如何混合这些表(数据)? Should I use the mysql UNION function or something else? 我应该使用mysql UNION函数还是其他? What is the appropriate code for this job? 这项工作的适当代码是什么?

Thanks... 谢谢...

You should use 你应该用

SELECT * FROM female ORDER BY age DESC LIMIT 20
UNION
SELECT * FROM male ORDER BY age DESC LIMIT 20

or 要么

SELECT * FROM
    (SELECT * FROM female
     UNION
     SELECT * FROM male)
ORDER BY age DESC LIMIT 20

Finally, a consideration: why do you use separate tables for males and females? 最后,要考虑一下:为什么要为男性和女性使用单独的表格? You caould use a single table with a column for sex... 您可以使用带有列的单个表进行性别...

Well, the most appropriate solution is to not have separate male and female tables, but rather to have one people table with a gender column. 好吧,最合适的解决方案是不要有单独的malefemale表,而是要有一个带有gender列的people表。 That way, you don't have to go messing around with unionizing tables and going crazy to merge them when, really, all these rows belong in the same table. 这样,实际上所有这些行都属于同一个表时,您不必费心去合并表并为合并它们而疯狂。 After all, if you're really all that interested in selecting only male or female people, that's what WHERE is for. 毕竟,如果您真的只对选择男性或女性感兴趣,那么这就是WHERE目的。

But if this is a legacy database with the schema set in stone, I feel your pain, and Marco's solution would do the trick :) 但是,如果这是一个架构固定的旧式数据库,我会感到很痛苦,而Marco的解决方案可以解决问题 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM