1

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

我有 3 个表格,ad_title、items 和 posted_ads

ad_title - title_id、title、item_id

项目 - item_id、ad_body、帐户

post_ads - post_id、title_id、item_id、帐户

我一直在尝试获取未在某个帐户中发布但未成功的 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'
)

任何帮助,将不胜感激。

谢谢

4

1 回答 1

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
) 

但这也可以用 a 来完成,在LEFT JOIN中寻找NULLs 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
于 2013-02-25T00:58:37.230 回答