Mysql,多个查询与JOIN和SORT BY结合使用

时间:2012-12-02 13:37:13

标签: php mysql sql

我是MySQL的初学者并且已经陷入困境。 我想我必须制作某种“高级”子查询来解决我的问题,但我无法弄清楚如何。有人能帮助我吗?

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

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

第二个 查询在表格“kontering_annons for each”id_annons“中显示 last 条目。(在我的情况下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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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然后JOINkontering_annons一起,通过id_kontering_a加入该表,仅选择该表中具有最后kid_kontering_a = km.maxid的所有数据。

请注意:我使用INNER JOIN然后使用两个LEFT JOIN来保持LEFT JOIN,否则LEFT JOIN然后INNER JOIN要获得最大ID,它将是INNER JOIN