我应该使用 UNION 还是其他东西来从多个表中选择数据?
我的 mysql 数据库中有两个表:female 和 male。它们各有 3 列:id、name 和 age。 我想要显示一个 html 表,其中包含两个表的数据。
我有这些代码片段:
$result = mysql_query("SELECT * FROM female ORDER BY age DESC LIMIT 20");
while($row = mysql_fetch_array($result))
{
$age = $row['age'];
$name = $row['name'];
}
那么
$result01 = mysql_query("SELECT * FROM male ORDER BY age DESC LIMIT 20");
while($row01 = mysql_fetch_array($result01))
{
$age01 = $row01['age'];
$name01 = $row01['name'];
}
我应该如何混合这些表(数据)?我应该使用 mysql UNION
函数还是其他函数?适合这项工作的代码是什么?
谢谢...
I have two tables in my mysql database: female and male. They both have 3 columns each: id, name and age.
I want a html table to be displayed with both table's data in it.
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? What is the appropriate code for this job?
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
or
最后,一个考虑因素:为什么对男性和女性使用单独的表格?您可以使用带有性别列的单个表......
You should use
or
Finally, a consideration: why do you use separate tables for males and females? You caould use a single table with a column for sex...
那么,最合适的解决方案是不要有单独的
male
和female
表,而是有一个带有gender 的
列。这样,当所有这些行实际上都属于同一个表时,您就不必费力地合并表并疯狂地合并它们。毕竟,如果您真的只对选择男性或女性感兴趣,那么people
表WHERE
就适合这样做。但如果这是一个具有固定模式的遗留数据库,我会感受到你的痛苦,并且 Marco 的解决方案 可以解决问题:)
Well, the most appropriate solution is to not have separate
male
andfemale
tables, but rather to have onepeople
table with agender
column. 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 whatWHERE
is for.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 :)