4

我是 MySQL 的初学者并且被卡住了。我想我必须做一些“高级”子查询来解决我的问题,但我不知道怎么做。有人可以帮助我吗?

第一个查询连接三个表,“annons”、“kontering_annons”和“member”。结果是唯一的“annons.id”条目。(在我的情况下是 3 个结果)。问题是我需要为每个唯一的“annons.id”找到表“kontering_annons”中的最后一个条目。这个查询没有。

SELECT  annons.id, annons.id_user, member.saldo, member.id,
kontering_annons.id_annons, kontering_annons.dat_bet_till, 
kontering_annons.id_kontering_a, kontering_annons.dat_ut_member
FROM annons
LEFT JOIN kontering_annons 
ON kontering_annons.id_annons = annons.id
LEFT JOIN member
ON member.id = annons.id_user
WHERE (annons.status='3' OR annons.status='4')
AND annons.typ='d'
AND annons.startar < NOW() - 48*60*60
AND kontering_annons.dat_bet_till < CURRENT_DATE()
AND member.saldo >= $day_price
GROUP BY annons.id

第二个查询为每个“id_annons”提供表“kontering_annons”中的最后一个条目。(在我的例子中,有 18 个结果)。我想我需要将此查询与上面的查询结合起来,才能找到只有三个唯一条目最新的条目 ID。但是如何?

SELECT a.*
FROM kontering_annons a
INNER JOIN (SELECT id_annons, dat_bet_till, max(id_kontering_a) 
AS maxid 
FROM kontering_annons 
GROUP BY id_annons) 
AS b 
ON a.id_kontering_a = b.maxid
4

2 回答 2

0

您可以将以下查询保存到临时表中。

SELECT a.*
FROM kontering_annons a
INNER JOIN (SELECT id_annons, dat_bet_till, dat_ut_member, 
max(id_kontering_a) AS maxid 
FROM kontering_annons 
GROUP BY id_annons) AS b 
ON a.id_kontering_a = b.maxid
AND a.dat_bet_till < CURRENT_DATE()

然后使用替换 kontering_annons 表的主查询加入临时表。

SELECT  annons.id, annons.id_user, member.saldo, member.id,
tempT.id_annons, tempT.dat_bet_till, 
tempT.id_kontering_a, tempT.dat_ut_member
FROM annons
LEFT JOIN tempT 
ON tempT.id_annons = annons.id
LEFT JOIN member
ON member.id = annons.id_user
WHERE (annons.status='3' OR annons.status='4')
AND annons.typ='d'
AND annons.startar < NOW() - 48*60*60
AND member.saldo >= $day_price
GROUP BY annons.id
于 2012-12-02T13:57:37.627 回答
0

试试这个:

SELECT  
  a.id, 
  a.id_user, 
  m.saldo, 
  m.id,
  k.id_annons, 
  k.dat_bet_till, 
  k.id_kontering_a, 
  k.dat_ut_member
FROM annons a
INNER JOIN
(
    SELECT 
      id_annons, 
      dat_bet_till, 
      max(id_kontering_a) AS maxid 
    FROM kontering_annons 
    GROUP BY id_annons
) km ON a.id = km.id_annons
LEFT JOIN kontering_annons k  ON k.id_annons     = km.id_annons 
                             AND k.id_kontering_a = km.maxid 
LEFT JOIN member           m  ON m.id            = a.id_user
WHERE (a.status='3' OR a.status='4')
AND a.typ='d'
AND a.startar < NOW() - 48*60*60
AND k.dat_bet_till < CURRENT_DATE()
AND m.saldo >= $day_price

我在这里所做的是带有以下内容INNER JOIN的表格annons

    SELECT 
      id_annons, 
      dat_bet_till, 
      max(id_kontering_a) AS maxid 
    FROM kontering_annons 
    GROUP BY id_annons

ON a.id = km.id_annons然后JOIN它,通过加入它kontering_annons,只选择该表中最后一个的所有数据。id_kontering_akid_kontering_a = km.maxid

请注意:我使用INNER JOIN了两个LEFT JOIN来保留它,LEFT JOIN否则如果你这样做了,LEFT JOIN那么INNER JOIN它会是一个INNER JOIN.

于 2012-12-02T13:58:48.483 回答