从1表中获取值,这些表也在另一个表中,而不在另一个表中

时间:2013-02-25 00:50:50

标签: php mysql sql

我正在尝试只获取尚未从MySQL数据库发布的广告。

我有3个表,ad_title,items和posting_ads

ad_title - title_id,title,item_id

项目 - item_id,ad_body,accounts

posted_ads - post_id,title_id,item_id,account

我一直在尝试获取尚未在特定帐户中发布的ad_titles /项目列表但未成功。这是我的疑问:

SELECT * 
FROM 
  ad_title t
  JOIN items l 
   ON ( l.item_id= t.item_id
   AND l.accounts LIKE  '%myaccount@email.com%' ) 
WHERE NOT EXISTS (
  SELECT q.item_id
  FROM posted_ads q
  WHERE q.acc_used =  'myaccount@email.com'
)

任何帮助都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:1)

在查询的当前表单中,您应该在子查询中使用ad_title.items_id NOT IN (...),因为NOT EXISTS子查询在WHERE中不包含任何内容以将其与外部查询相关联

SELECT
  /* Don't actually SELECT * in a JOIN query. Be explicit about the needed columns */
  /* especially since you have item_id in all tables */
  t.*,
  l.* 
FROM 
  ad_title t
  JOIN items l 
   ON ( l.item_id= t.item_id
   AND l.accounts LIKE  '%myaccount@email.com%' ) 
WHERE
  /* Find item_id via NOT IN */ 
  t.item_id NOT IN (
    SELECT q.item_id
    FROM posted_ads q
    WHERE q.acc_used =  'myaccount@email.com'
  )

要使其作为NOT EXISTS工作,您需要将子查询与外部查询相关联:

WHERE NOT EXISTS (
  SELECT q.item_id
  FROM posted_ads q
  WHERE 
    q.acc_used =  'myaccount@email.com'
    /* Need relation to the outer query */
    AND q.item_id = l.item_id
) 

但这也可以通过LEFT JOIN来完成,在NULL中查找posted_ads。这可能是最有效的方法:

SELECT
  /* Don't SELECT * in a JOIN query. Be explicit about the needed columns */
  t.*,
  l.* 
FROM 
  ad_title t
  JOIN items l 
   ON ( l.item_id= t.item_id
   AND l.accounts LIKE  '%myaccount@email.com%' ) 
  LEFT JOIN 
    posted_ads q 
      ON l.item_id = q.item_id
      AND q.acc_used = l.accounts
WHERE
  /* NULL in the posted_ads table means it doesn't exist there */ 
  posted_ads.item_id IS NULL
相关问题