表'2_1_journal'
NumberRenamed
-------------
1
2
3
表'2_1_paidused'
NumberRenamed
-------------
1
2
想要从每个表中选择最后一个值,并获得具有2个值的数组。
基于示例,创建了这样的代码
SELECT 2_1_journal.NumberRenamed, 2_1_paidused.NumberRenamed
FROM 2_1_journal
LEFT JOIN 2_1_paidused ON 2_1_journal.NumberRenamed = 2_1_paidused.NumberRenamed
ORDER BY NumberRenamed DESC LIMIT 1
$stmt->execute();
$ArrayWithTwoNumbers = $stmt->fetchColumn();
但是得到错误SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'NumberRenamed' in order clause is ambiguous
。
如果删除ORDER BY NumberRenamed DESC LIMIT 1
获取值1
(来自2_1_journal.NumberRenamed
的第一个值)。
请建议需要纠正的内容。
简单的方法是使用SELECT
进行2次查询。但据我所知,更好地节省资源以使用一个查询....
已更改为ORDER BY 2_1_journal.NumberRenamed DESC LIMIT 1
并获得123
已更改为
(SELECT NumberRenamed FROM 2_1_journal
UNION
SELECT NumberRenamed FROM 2_1_paidused)
ORDER BY NumberRenamed DESC LIMIT 1
获取SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION SELECT NumberRenamed FROM 2_1_paidused) ORDER BY NumberRenamed DESC LI' at line 2
已更改为
(SELECT NumberRenamed FROM 2_1_journal )
UNION ALL
(SELECT NumberRenamed FROM 2_1_paidused)
ORDER BY NumberRenamed DESC LIMIT 1
没有错误,但结果不符合预期(从表2_1_paidused获取最后一个值)。如何从表2_1_journal中获取最后一个值?
似乎这是解决方案
(SELECT NumberRenamed as Number1 FROM 2_1_journal ORDER BY Number1 DESC LIMIT 1)
UNION
(SELECT NumberRenamed as Number2 FROM 2_1_paidused ORDER BY Number2 DESC LIMIT 1)
和$stmt->fetchAll();
获取
[0] => Array
(
[Number1] => 3
[0] => 3
)
[1] => Array
(
[Number1] => 2
[0] => 2
)
值正确(如预期的那样)。但是为什么在[0]
和[1]
中有[Number1]
?预计在[1]
[Number2]
答案 0 :(得分:1)
测试类似:
select
(select max(NumberRenamed) from 2_1_journal) max1,
(select max(NumberRenamed) from 2_1_paidused) max2
它比2个不同的查询好一点,唯一的区别是它有1个远程调用(网络开销),但使用2个不同的查询会产生2个远程调用。
答案 1 :(得分:0)
添加任意一个表名,如2_1_journal.NumberRenamed
SELECT 2_1_journal.NumberRenamed, 2_1_paidused.NumberRenamed
FROM 2_1_journal
LEFT JOIN 2_1_paidused ON 2_1_journal.NumberRenamed = 2_1_paidused.NumberRenamed
ORDER BY 2_1_journal.NumberRenamed DESC LIMIT 1