我只是MySQL的新手,我想编写一份SELECT语句,为居住在印第安纳州,俄亥俄州,密歇根州和伊利诺伊州的客户返回客户ID和客户名称(按字母顺序排列),其名称以字母A或B.
这是使用DESCRIBE CUSTOMER_TBL的CUSTOMER_TBL结构;
Name Null? Type
-------------------------------------------------------------
CUST_ID NOT NULL VARCHAR2(10)
CUST_NAME NOT NULL VARCHAR2(30)
CUST_ADDRESS NOT NULL VARCHAR2(20)
CUST_CITY NOT NULL VARCHAR2(12)
CUST_STATE NOT NULL CHAR(2)
CUST_ZIP NOT NULL CHAR2(5)
CUST_PHONE NUMBER(10)
CUST_FAX NUMBER(10)
这是我的解决方案。我只需要知道我是否正确。感谢
SELECT CUST_ID,CUST_NAME FROM CUSTOMER_TBL
WHERE IN('Indiana','Ohio','Ohio','Michigan','Illinois') AND WHERE LIKE(A% OR B%)
ORDER BY CUST_ID,CUST_NAME
答案 0 :(得分:1)
SELECT CUST_ID,CUST_NAME FROM CUSTOMER_TBL
WHERE CUST_STATE IN('Indiana','Ohio','Ohio','Michigan','Illinois') AND (CUST_NAME LIKE 'A%' OR CUST_NAME LIKE 'B%')
ORDER BY CUST_ID,CUST_NAME
答案 1 :(得分:0)
您的CUST_STATE
是CHAR(2)
列,因此我假设它包含州代码,而不是州名。所以你应该使用州代码来代替印第安纳州,俄亥俄州等。
SELECT CUST_ID, CUST_NAME
FROM CUSTOMER_TBL
WHERE CUST_STATE IN ('IN','OH','MI','IL') AND (
CUST_NAME LIKE 'A%' OR
CUST_NAME LIKE 'B%'
)
ORDER BY CUST_NAME
如果错误,请更正州代码。
答案 2 :(得分:0)
您的查询中有几个问题:
WHERE
语句中嵌套条件时,请勿重复where itslef。因此,您的查询应如下所示:
SELECT CUST_ID, CUST_NAME
FROM CUSTOMER_TBL
WHERE CUSTOMER_City IN('Indiana','Ohio','Ohio','Michigan','Illinois')
AND ( CUST_NAME LIKE 'A%' OR CUST_NAME LIKE 'B%' )
ORDER BY CUST_ID,CUST_NAME