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

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

问题描述

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

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

示例可能是以下设置.

tbl马德里

   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天全站免登陆