子查询有两列

时间:2014-07-13 13:08:01

标签: mysql

我有两张桌子,如下:

a.id,a.created,a.b
b.id,b.name,b.created

我希望表 b 中的所有记录按 a.created 时间戳排序。

我一直尝试以下方法:

SELECT b.id, b.name FROM b JOIN a ON a.b = b.id ORDER BY b.created DESC

但它始终从 b 返回多条记录,而我真正想要的只是 a 的一个匹配 b

我尝试使用SELECT子查询:

SELECT b.id, b.name, (SELECT a.created AS a_c FROM a WHERE
a.b = b.id) AS a_c FROM b ORDER BY a_c DESC

但我也希望能够拉出a.id.

我可以使用JOIN语句还是应该使用两个子查询?这在我的应用程序中将是一个非常重要的功能,所以我希望性能高于标准!

4 个答案:

答案 0 :(得分:1)

SELECT b.id AS bid, b.name, a.id AS aid, a.created
FROM b
JOIN (SELECT a1.id, a1.b, a1.created
      FROM a AS a1
      JOIN (SELECT id, MAX(created) AS maxcreate
            FROM a
            GROUP BY id) AS a2
      ON a1.id = a2.id AND a1.created = a2.maxcreate) AS a
ON b.id = a.b
ORDER BY a.created DESC

子查询获取a中的行,其中包含每个id的最新创建日期。然后你加入b

答案 1 :(得分:1)

select b.id, b.name, a.id a_id, a.created
from b join (
    select b, max(a.created) max_created
    from a
    group by b
) t1 on t1.b = b.id
join a on a.b = b.id and a.created = t1.max_created
order by a.created desc

答案 2 :(得分:1)

select
   b.id
  ,b.name
  ,b.created as b_created
  ,a.created as a_created 
from b
left join a
join (
   select b, max(created) as max_creatd
   from a
   group by b
)a_min
   on a_min.b = a.b
  and a_min.max_creatd = a.created
   on a.b   = b.id

对于这些数据集(SQL Server语法避免编写大量DDL):

a as (select * from (values
     ('A1','20140701 23:11:59', 'B1')
    ,('A2','20140701 22:11:59', 'B1')
  )a(id,created,b)

b as ( select * from (values
    ('B1', 'Bob', '20140701 11:59:59')
   ,('B2', 'Bub', '20140701 10:59:59')
  )b(id,name,created)

返回以下内容:

id   name b_created         a_created
---- ---- ----------------- -----------------
B1   Bob  20140701 11:59:59 20140701 23:11:59
B2   Bub  20140701 10:59:59 NULL

(2 row(s) affected)

答案 3 :(得分:0)

我最后只是以suggested in this answer加入表格。

SELECT b.id, b.name, a.id AS a_id FROM b JOIN a ON
a.id = (SELECT a.id FROM a WHERE a.b=b.id ORDER BY 
a.created DESC LIMIT 1)