如何在没有子查询的情况下为以下查询编写sql

时间:2016-10-11 00:19:57

标签: sql

<body>

<input type="button" id="bestValue" value="Best Value"></div>
<p id="msg">hello</p>


<script>
var item1 = {name: "bigMac", price: 3.99, calories: 530};
var item2 = {name: "filetOFish", price: 3.79, calories: 390};
var item3 = {name: "doubleCheeseburger", price: 1.59, calores: 430};
var item4 = {name: "chickenMcNuggets", price: 4.49, calores: 190};

var meals = [item1, item2, item3, item4];


function init() {
var bestValue = document.getElementById('bestValue');
bestValue.onclick = cheapestItem(meals);
}

window.onload = init;

// return name of cheapest item on menu
function cheapestItem(menu) {
	var msg = document.getElementById('msg');

	var cheapest = menu[0].price;
	var item;

	for (var i = 0; i < menu.length; i++) {
		if (menu[i].price < cheapest) {
			cheapest = menu[i].price;
			item = menu[i].name;
		} 
	}
	console.log(item); 
	msg.innerHTML = "The cheapest item is " + item;
}

</script>
</body>

1 个答案:

答案 0 :(得分:3)

首先,学会使用正确的,明确的JOIN语法。

然后,如果您假设最高费用只出现一次,您可以这样做:

SELECT C.pid
FROM Catalog C JOIN
     Suppliers S
     ON C.sid = S.sid
WHERE S.sname = 'Yosemite Sham'
ORDER BY  c.Cost DESC
FETCH FIRST 1 ROW ONLY ;

请注意,最后一个子句是ANSI标准SQL。有些数据库使用其他方法来实现相同的功能。

没有这个假设,基本上所有合理的方法都使用子查询。这是一个没有:

SELECT C.pid
FROM Catalog C JOIN
     Suppliers S
     ON C.sid = S.sid LEFT JOIN
     Catalog C2
     ON C2.sid = C.sid AND
        C2.Cost > C.Cost
WHERE S.sname = 'Yosemite Sham' AND c2.Cost IS NULL
ORDER BY c.Cost DESC;

注意:这假设sidsname为1-1。这是一种便利(可能是真的)并且有助于避免额外加入Suppliers