我试图以下列方式选择一些数据:
SELECT column
FROM table
WHERE a = a1
AND (b = b1 OR b = b2 OR b = b3);
我想要它做的是如果b不等于b1,检查b = b2。但是,如果b = b1,请不要检查其他条件。 此select语句的结果必须只是一个条目。但是,在我没有的语句中,它会检查所有这三个条件,有时会返回多行。同样,我希望它停止检查条件是否为真。
有关如何实施的任何想法?我尝试了案例,但没有成功......
提前谢谢!
EDIT 这是我想要运行的实际查询。
INSERT INTO shipment_flights
(airlinename, flt_no, flt_date, destination, phone, depttime, arrivaltime, pcs, weight)
SELECT st.airlinename, flightno, flightdate, destination,
(SELECT phone
FROM carrierlocations
WHERE carriers_carrierid = (select carrierid from carriers where airlinename = st.airlinename)
AND (city = destination OR (city != destination AND
city = (SELECT city FROM airports WHERE iataid =
(SELECT airports_iataid FROM ratelegs
WHERE shipments_shipid = c.shipments_shipid))
))) phone,
depttime, arrivaltime, sum(linepcs), sum(lineweight)
FROM segment_times st
JOIN contents2flights c2f
ON st.flightid = c2f.segments_flights_flightid
AND st.segmentid = c2f.segments_segmentid
JOIN contents c
ON c.lineno = c2f.contents_lineno
AND c.shipments_shipid = c2f.contents_shipments_shipid
WHERE c.shipments_shipid = var_shipid
GROUP BY flightid
ORDER BY flightdate, depttime;
以下是示例输出:
airlinename flt_no flt_date destination phone pcs weight
Everts Air Alaska CH1 2008-02-20 Hughes 9074502351 24 2121
查询将一堆航班数据插入临时表。我遇到的问题是获取某个地点的电话号码。这部分内容如下:
(SELECT phone
FROM carrierlocations
WHERE carriers_carrierid = (select carrierid from carriers where airlinename = st.airlinename)
AND (city = destination OR (city != destination AND
city = (SELECT city FROM airports WHERE iataid =
(SELECT airports_iataid FROM ratelegs
WHERE shipments_shipid = c.shipments_shipid))))) phone
在Amit Bhargava建议的查询中,只有临时表中有一行时才会得到正确的结果。如果还有更多,则会在选择手机部分时抛出错误。
“错误代码:1242。子查询返回超过1行”
答案 0 :(得分:3)
通过使用IF()+ IF()+ IF(),并且测试sum = 1可以防止大量额外的而不是其他标准。如果2或全部3相同,则总和将大于1.如果它们都不匹配,则结果为0.这应该完全符合您的要求。
SELECT column
FROM table
WHERE a = a1
AND if( b = b1, 1, 0 )
+ if( b = b2, 1, 0 )
+ if( b = b3, 1, 0 ) = 1
或者......在ypercube的帮助下,我一直忘记逻辑测试分别返回1或0表示真/假,例如......
SELECT column
FROM table
WHERE a = a1
AND (b = b1) + (b = b2) + (b = b3) = 1
答案 1 :(得分:1)
请尝试以下方法。不是最优雅的解决方案,但它应该有效。
SELECT column
FROM table
WHERE a = a1
AND (b = b1 OR (b != b1 AND (b = b2 OR (b != b2 AND b = b3))))