【问题标题】:How get 1 row from join 2 table where a.user_id = 'aa' and order by the last time如何从连接 2 表中获取 1 行,其中 a.user_id = 'aa' 并在最后一次订购
【发布时间】:2017-01-24 08:30:12
【问题描述】:

我有两张桌子,例如

TABEL_AA

id   uid   user_id   name   date
1    A11      aa     BBBB   2017-01-01 00:01:01
2    A13      aa     cccc   2017-01-01 00:01:05

TABEL_BB(临时)

id   uid   user_id   name   date
1    A12      aa     BBBB   2017-01-01 00:01:02
2    A14      aa     cccc   2017-01-01 00:01:08

从 2 表中我得到 1 最后一行,其中 user_id = 'aa' 和 ORDER BY date DESC

结果来自TABEL BB

id   uid   user_id   name   date
2    A14      aa     cccc   2017-01-01 00:01:08

反之亦然.. 如果最后一条记录在 TABEL AA 中

我使用这个查询,但总是出错:

"SELECT 
    'a.uid' 
 FROM TABEL_AA a 
    LEFT JOIN TABLE_BB b ON a.user_id = b.user_id 
 WHERE a.user_id = 'aa' LIMIT 1 ORDER BY date DESC";

错误:

"Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY date DESC' at line 1"

谢谢你的帮助..

【问题讨论】:

  • 请发布您遇到的错误。
  • @Rajat Mishra 这是我的错误“警告:PDOStatement::execute(): SQLSTATE[42000]: 语法错误或访问冲突:1064 您的 SQL 语法有错误;请查看相应的手册到您的 MariaDB 服务器版本,以便在第 1 行的“ORDER BY date DESC”附近使用正确的语法”
  • 如果你想订购一些东西,这需要在结果集中。
  • 不管放在哪个表里,好像都想获取最新的行吧?

标签: mysql


【解决方案1】:

您需要在排序前加入表格,并使用限制:

select * from table_aa union select * from table_bb
where `user_id` = 'aa'
order by date_whatever desc
limit 1

我已将您的 date 列重命名为 date_whatever,因为 date 是 MariaDB 中的保留字。

这里是SQLFiddle 来试试这个答案

【讨论】:

  • aa 应该在引号中而不是转义。
  • @Bustkiller .. 谢谢
【解决方案2】:

您的查询是错误的,请始终在查询结束时使用限制,并且不要在选择中使用引号,例如“a.uid”,这是修改后的查询:-

"SELECT 
    a.uid 
 FROM TABEL_AA a 
    LEFT JOIN TABLE_BB b ON a.user_id = b.user_id 
 WHERE a.user_id = 'aa' ORDER BY date DESC LIMIT 1";

此外,您的查询对于您所询问的内容和数据看起来是错误的,我认为应该是:-

select uid FROM
(Select * from TABEL_AA 
UNION
Select * from TABEL_BB) result 
order by date desc limit 1

【讨论】:

  • 即使这是真的,也不是问题。
  • 那么问题出在哪里,因为您的错误日志显示'ORDER BY date DESC'附近的问题
  • 需要 where user_id = 'aa'?
  • @RakeshKumar TABEL_BB 之后的“结果”是什么)?是别名?
  • 是的结果是别名
猜你喜欢
  • 2020-06-09
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
相关资源
最近更新 更多