简体   繁体   English

如何显示两个不相关的表中的数据?

[英]How can I display data from two unrelated tables?

I have two unrelated tables in a MYSQL database. 我在MYSQL数据库中有两个不相关的表。 I want to select and display data from both of them. 我想从两者中选择并显示数据。

As an example, the tables looks like this: 例如,这些表如下所示: 单独的表

I would like to display the results on my site, organised alphabetically, like this: 我想按字母顺序将结果显示在我的网站上,如下所示: 结果表

The ID from each table is used to refer to a photo of the cat or dog. 每个表中的ID用于引用猫或狗的照片。 I haven't had much luck with JOIN statements, would a UNION work in this scenario? 我对JOIN语句不太满意,在这种情况下UNION可以工作吗?

Any help much appreciated. 任何帮助,不胜感激。

SELECT Alpha, Name, CONVERT(Cat_Id, CHAR(50)) AS Cat_Id, '' AS Dog_Id
FROM Cat
UNION ALL
SELECT Alpha, Name, '' AS Cat_Id, CONVERT(Dog_Id, CHAR(50)) AS Dog_Id
FROM Dog
ORDER BY Alpha

A few comments: 一些评论:

Strictly speaking, if we want to show empty string for missing cat or dog IDs, then we need to cast the Cat_Id or Dog_Id columns to CHAR , because all values in a column need to be the same type. 严格来说,如果我们想为缺少的猫或狗ID显示空字符串,则需要将Cat_IdDog_IdCat_Id Dog_IdCHAR ,因为列中的所有值都必须为同一类型。

It is not necessary to wrap the UNION query to use ORDER BY and sort by the Alpha column, rather we can just add ORDER BY to the end. 不必包装UNION查询以使用ORDER BY并按Alpha列进行排序,而是我们可以在末尾添加ORDER BY

SELECT Alpha,Name,Cat_ID,'' as Dog_ID
FROM Cat
UNION ALL
SELECT Alpha,Name,'' as Cat_ID,Dog_ID
FROM Dog

I would combine the two tables into one table using the fields: 我将使用字段将两个表合并为一个表:

ID   Type   Name   Alpha

The type field would be either cat or dog then the rest will fill in as you have. type字段可以是cat或dog,其余的将根据您的需要填写。 This also allows you to add additional animal types in the future without having to change your database. 这也使您将来可以添加其他动物类型,而不必更改数据库。 Then it is a simple select when displaying your data. 这是显示数据时的简单选择。

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

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