SQL:在一个查询中有两个选择语句 [英] SQL: Two select statements in one query

查看:278
本文介绍了SQL:在一个查询中有两个选择语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个查询中从两个SQL表中选择信息,尽管该信息是不相关的,所以不存在潜在的联接.

I want to select information from two SQL tables within one query, the information is unrelated though, so no potential joints exist.

一个示例可能是以下设置.

An example could be the following setup.

tblMadrid

tblMadrid

   id | name    | games | goals
    1 | ronaldo | 100   | 100
    2 | benzema | 50    | 25
    3 | bale    | 75    | 50
    4 | kroos   | 80    | 10

tbl巴塞罗那

   id | name    | games | goals
    1 | neymar  | 60    | 25
    2 | messi   | 150   | 200
    3 | suarez  | 80    | 80
    4 | iniesta | 40    | 5

我想查询一个能给我以下内容的东西:

I want to have a query that gives me the following:

name    | games | goals
messi   | 150   | 200
ronaldo | 100   | 100

我尝试遵循以下逻辑:单个查询中有多个选择语句但是以下代码不起作用:

I tried to follow this logic: Multiple select statements in Single query but the following code did not work:

USE Liga_BBVA

SELECT (SELECT name,
               games,
               goals
        FROM   tblMadrid
        WHERE  name = 'ronaldo') AS table_a,
       (SELECT name,
               games,
               goals
        FROM   tblBarcelona
        WHERE  name = 'messi')   AS table_b
ORDER  BY goals 

对此有何建议?谢谢 信息:足球只是一个简化的示例.实际上,不可能将两个表都放在一个表中并有一个新的团队"列.这两个表的结构完全不同,但是我需要一些与本示例的特征相匹配的文件.

Any advice on this one? Thanks Info: The football stuff is just a simplifying example. In reality it is not possible to put both tables into one and have a new "team" column. The two tables have completely different structures, but I need something that matches the characteristics of this example.

推荐答案

您可以执行以下操作:

 (SELECT
    name, games, goals
    FROM tblMadrid WHERE name = 'ronaldo')
 UNION
 (SELECT
    name, games, goals
    FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;

例如,参见: https://dev.mysql.com/doc/refman/5.0/en/union.html

这篇关于SQL:在一个查询中有两个选择语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆