将其他列添加到INNER JOIN SQL查询中

时间:2013-02-23 10:57:12

标签: mysql sql inner-join

我有以下INNER JOIN查询,您可以在小提琴here中看到它。

SELECT  b.*, c.date2
FROM    (
            SELECT a.work, a.amount, 
                   COUNT(*) totalCount, 
                   SUM(Amount) totalAmount
            FROM tableName a
            GROUP BY a.work, a.amount
        ) b
        INNER JOIN
        (
            SELECT a.work, a.amount, DATE_FORMAT(Date,'%D %M %Y') date2,
                    date
            FROM tableName a
        ) c ON b.work = c.work and b.amount=c.amount
ORDER BY b.work, b.totalCount, c.date

我想在查询中添加另一个名为“url”的列,其工作方式与日期列相同,即它在每个行的“url”列中返回不同的值。您可以在小提琴here中找到包含新列的架构。我不确定如何调整查询以返回具有不同“url”值的额外列。我尝试了一些方法,但无法使其正常工作。

2 个答案:

答案 0 :(得分:2)

你可以尝试这个......

    SELECT  b.*, c.date2, c.url
    FROM    (
            SELECT a.work, a.amount, 
                   COUNT(*) totalCount, 
                   SUM(Amount) totalAmount
            FROM tableName a
            GROUP BY a.work, a.amount
        ) b
        INNER JOIN
        (
            SELECT a.work, a.amount, DATE_FORMAT(Date,'%D %M %Y') date2,
                    date, url
            FROM tableName a
        ) c ON b.work = c.work and b.amount=c.amount
    ORDER BY b.work, b.totalCount, c.date

答案 1 :(得分:2)

它可以写得更短

 SELECT a.work, a.amount, 
                   COUNT(*) totalCount, 
                   SUM(Amount) totalAmount, url, DATE_FORMAT(Date,'%D %M %Y')
            FROM tableName a
            GROUP BY a.work, a.amount, DATE_FORMAT(Date,'%D %M %Y')