Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 2表查询正确的协议_Php_Mysql - Fatal编程技术网

Php 2表查询正确的协议

Php 2表查询正确的协议,php,mysql,Php,Mysql,我有一个需要修改的搜索结果查询,这样它就不会显示已经销售的产品。下面是当前存在的未修改的select语句: SELECT id, cid, sid, posttitle, postdetails, city, `state`, zipcode FROM posts ORDER BY datepublished DESC 我需要修改它,以便它查看DetailProductID`下的orderdetails表,查看它是否存在,以及它是否存在,以便现在显示它;所以在英语中,本质上是这样的: SE

我有一个需要修改的搜索结果查询,这样它就不会显示已经销售的产品。下面是当前存在的未修改的select语句:

SELECT id, cid, sid, posttitle, postdetails, city, `state`, zipcode 
FROM posts 
ORDER BY datepublished DESC
我需要修改它,以便它查看DetailProductID`下的
orderdetails表,查看它是否存在,以及它是否存在,以便现在显示它;所以在英语中,本质上是这样的:

SELECT id, cid, **etc** 
FROM posts 
WHERE posts.id NOT IN orderdetails.DetailProductID
或者使用一个巧妙的左连接

SELECT 
posts.id, posts.cid, posts.sid, posts.posttitle, posts.postdetails, posts.city, posts.state, posts.zipcode 
FROM posts 
LEFT JOIN orderdetails ON orderdetails.DetailProductID = posts.id
where orderdetails.DetailProductID is null
ORDER BY posts.datepublished DESC

我会使用左连接,因为它对于更大的数据性能更好。“不在”状态可能有成百上千个ID,这将减慢速度。此外,从长远来看,随着数据的增长,它将进一步降低性能。基本上,对于“in”语句中的20多个项,我将使用join。此外,通常不建议使用子查询。
SELECT 
id, cid, sid, posttitle, postdetails, city, state, zipcode 
FROM posts 
where posts.id not in (select DetailProductID from orderdetails)
ORDER BY datepublished DESC
SELECT 
posts.id, posts.cid, posts.sid, posts.posttitle, posts.postdetails, posts.city, posts.state, posts.zipcode 
FROM posts 
LEFT JOIN orderdetails ON orderdetails.DetailProductID = posts.id
where orderdetails.DetailProductID is null
ORDER BY posts.datepublished DESC