我在试着简化一些mysql。我有三个选择和三张桌子:

SELECT pageid FROM thepage WHERE DATE(createdate)='2011-11-09' ORDER BY createdate DESC

SELECT urlid FROM themix WHERE pageid=...

SELECT link FROM theurl WHERE urlid=...

给定一个createdate,它将获取所有的pageid,然后转到第二个表并获取这些pageid的所有urlid,然后获取所有这些urlid的链接。我现在正在使用while循环,但怀疑有一种方法可以将它们合并为一个。
有什么想法吗?

最佳答案

SELECT p.pageid
     , u.link
FROM thepage p INNER JOIN themix m
    ON p.pageid = m.pageid
INNER JOIN theurl u
    ON m.urlid = u.urlid
WHERE DATE(p.createdate) = '2011-11-09'
ORDER BY p.createdate DESC

我想应该玩这个把戏。如果只需要唯一的URL,请使用以下命令:
SELECT u.link
FROM thepage p
  INNER JOIN themix m
    ON p.pageid = m.pageid
  INNER JOIN theurl u
    ON m.urlid = u.urlid
WHERE DATE(p.createdate) = '2011-11-09'
GROUP BY m.urlid
ORDER BY MIN(p.createdate) DESC

旁注
WHERE DATE(p.createdate) = '2011-11-09'

必须扫描整个page表并为每一行调用DATE()函数。有两种方法可以加快速度:
createdate更改为DATE(从现在的DATETIMETIMESTAMP)并使用:
WHERE p.createdate = '2011-11-09'

或者保持原样使用:
WHERE p.createdate >= '2011-11-09'
  AND p.createdate < '2011-11-10'

表名和列名最好不带前缀或后缀,比如the。这不是越来越清楚了吗(即使没有化名)?
SELECT url.link
FROM page
  INNER JOIN mix
    ON page.pageid = mix.pageid
  INNER JOIN url
    ON mix.urlid = url.urlid
WHERE DATE(page.createdate) = '2011-11-09'
ORDER BY page.createdate DESC

10-06 00:50