开发者

MySQL WHERE statement with cross table comparisons

开发者 https://www.devze.com 2023-03-13 16:50 出处:网络
The MySQL statement below gives me three times the same result because I need to select all the data from the different tables to do the comparisons. How can I tell MySQL that I only need one of those

The MySQL statement below gives me three times the same result because I need to select all the data from the different tables to do the comparisons. How can I tell MySQL that I only need one of those entries?

SELECT watchedItem开发者_如何学JAVAs.id FROM watchedItems, globalItems, bidGroups 
WHERE (watchedItems.bidGroupID IS NULL OR (watchedItems.bidGroupID IS NOT NULL AND bidGroups.bidGroupQty > 0))
AND watchedItems.aid = globalItems.aid
AND watchedItems.maxPrice > globalItems.currentPrice

Output:

ID
2
2
2


SELECT distinct(watchedItems.id) FROM ...

http://dev.mysql.com/doc/refman/5.0/en/select.html

"DISTINCT specifies removal of duplicate rows from the result set."


You need some joins:

SELECT watchedItems.id
FROM watchedItems
left join globalItems on watchedItems.bidGroupID = bidGroups.bidGroupID 
left join bidGroups on watchedItems.aid = globalItems.aid
WHERE (watchedItems.bidGroupID IS NULL OR bidGroups.bidGroupQty > 0)
AND watchedItems.maxPrice > globalItems.currentPrice

You were getting duplicates because there were three rows in the bidGroups table.

0

精彩评论

暂无评论...
验证码 换一张
取 消