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

发布于 2024-12-13 10:56:19 字数 648 浏览 0 评论 0原文

我的 mysql 数据库中有两个表:femalemale。它们各有 3 列:idnameage。 我想要显示一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫卆 2024-12-20 10:56:19

您应该使用

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

最后,一个考虑因素:为什么对男性和女性使用单独的表格?您可以使用带有性别列的单个表......

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...

爱你是孤单的心事 2024-12-20 10:56:19

那么,最合适的解决方案是不要有单独的 malefemale 表,而是有一个带有 gender 的 people 列。这样,当所有这些行实际上都属于同一个表时,您就不必费力地合并表并疯狂地合并它们。毕竟,如果您真的只对选择男性或女性感兴趣,那么 WHERE 就适合这样做。

但如果这是一个具有固定模式的遗留数据库,我会感受到你的痛苦,并且 Marco 的解决方案 可以解决问题:)

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. 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.

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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文