简体   繁体   中英

Combining three mysql statements

I'm trying to simplify some mysql. I have three selects and three tables:

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=...

Given a createdate, it gets all pageid's, then goes to a second table and gets all urlid's for those pageid's then gets the links for all those urlid's. I'm using while loops right now, but suspect there is a way to join them all into one.

Any ideas?

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

should do the trick i think. If you want only unique URLs, use this:

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

Sidenotes

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

will have to scan the whole page table and call the DATE() function for every row. You have two options to make it faster:

Change the createdate to DATE (from DATETIME or TIMESTAMP , that it is now) and use:

WHERE p.createdate = '2011-11-09'

or keep it as it is and use:

WHERE p.createdate >= '2011-11-09'
  AND p.createdate < '2011-11-10'

Table and column names are better without prefixes or suffixes like the the you have. Isn't this cleaner and clearer (even without the aliases)?

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

you already received some feedback in the comments to your post. you should really learn about the different types of sql joins

what you want should be achieved by something like this:

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

you should use the answers you got here as a starting point for your study on sql

SELECT link from theurl where (select urlid from themix where (select pageid from thepage where WHERE DATE(createdate)='2011-11-09' ORDER BY createdate DESC))

OR

SELECT link from theurl as tu , themix as tm, thepage as tp where tu.id=tm.urlid and tm.pageid=tp.id and DATE(createdate)='2011-11-09' ORDER BY createdate DESC

Any way it will give result.

您可以将3个查询嵌套到1个中,并使用IN表达式搜索多个ID。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM