希望有人可以提供帮助。
我有两个mysql select语句,每个语句都有效,但我现在需要将它们组合起来。
首先:
SELECT $shares.*, $shares_company.name AS name, SUM($shares.number) AS totalNumber, MAX(date) AS lastTransDate, $shares.timestamp AS lastUpdated FROM $shares
INNER JOIN
$shares_company WHERE $shares_company.id = $shares.company_id GROUP BY $shares.company_id
第二名:
SELECT $shares.price AS lastPrice
FROM $shares WHERE ($shares.company_id,$shares.date) IN
(SELECT $shares.company_id, MAX($shares.date) FROM $shares GROUP BY $shares.company_id)
我尝试了UNION
和UNION ALL
以及各种其他组合。
我被困住了!
更新
嗯,那是我现在的距离。这将返回所有正确的信息,除了我需要获取“数字”列的总和,我不知道将其插入查询的位置。 要插入的查询是:SELECT
SUM($shares.number) AS totalNumber FROM $shares
GROUP BY $shares.company_id
我现在的查询是:
SELECT $shares.price AS lastPrice,
$shares.date AS lastTransDate,
$shares.company_id,
$shares.id,
$shares.timestamp AS lastUpdated,
$shares_company.name
FROM $shares
INNER JOIN $shares_company
ON $shares_company.id = $shares.company_id
WHERE ($shares.company_id,$shares.date) IN
(SELECT $shares.company_id, MAX($shares.date)
FROM $shares
GROUP BY $shares.company_id)
感谢您的帮助。
答案 0 :(得分:0)
如果我理解正确,您需要在第一个查询中使用lastPrice结果。在这种情况下,我尝试这样的事情:
SELECT
$shares.*,
$shares_company.name AS name,
SUM($shares.number) AS totalNumber,
MAX(date) AS lastTransDate,
$shares.timestamp AS lastUpdated FROM $shares,
( SELECT $s.price
FROM $shares AS $s
WHERE $s.company_id = $shares.company_id
ORDER BY $s.date DESC
LIMIT 1
) AS lastPrice
INNER JOIN $shares_company
ON $shares_company.id = $shares.company_id
GROUP BY $shares.company_id
(注意:这是未经测试的,但原因应该是明确的:创建内部查询以选择此给定行的最后一个股价,然后将其作为另一列返回。)