2

我有 3 个表,想要进行 sql 查询以正确查看它们。

1.) 扎卡兹

id | Comment

2.) 托瓦尔

id  | id_clients | zakaz

3.) 用户

id | name

它们连接为:

zakaz.id = tovar.zakaz
tovar.id_clients = users.id

我想看看

zakaz.id | users.name  

但我只想限制每个 zakaz 1 个字符串,所以我做了:

SELECT zakaz.id, zakaz.comment, tovar.id_clients
    FROM zakaz
    JOIN tovar ON zakaz.id = tovar.zakaz
GROUP BY zakaz.id

然后我想加入用户,但它不起作用

SELECT zakaz.id, zakaz.comment, tovar.id_clients, users.name
    FROM zakaz
    JOIN tovar ON zakaz.id = tovar.zakaz
    GROUP BY zakaz.id
JOIN users ON users.id = tovar.id_clients
4

1 回答 1

3

它将显示最新的 idZakaz

SELECT  a.name, c.id
FROM    Users a
            INNER JOIN
            (
                SELECT id_clients, zakaz, MAX(id) maxID
                FROM Tovar
                GROUP BY id_clients, zakaz
            ) d 
                ON d.id_clients = a.id
            INNER JOIN Zakaz c
                ON d.zakaz = c.id
于 2012-09-01T11:25:10.167 回答