我有四个SQL查询:
SELECT `a017kstatus` FROM `a017` WHERE `a017kstatus`='A' AND `a017kjantina`='L';
SELECT `a017kstatus` FROM `a017` WHERE `a017kstatus`='A' AND `a017kjantina`='P';
SELECT `a017kstatus` FROM `a017` WHERE `a017kstatus`='TA' AND `a017kjantina`='L';
SELECT `a017kstatus` FROM `a017` WHERE `a017kstatus`='TA' AND `a017kjantina`='P';
如何将它们简化并在最好的情况下组合成单个查询?
答案 0 :(得分:0)
假设您想要获得包含所有四个查询结果的结果集,您可以将它们UNION
放在一起。但是我们可以使用一个查询进一步简化:
SELECT a017kstatus
FROM a017
WHERE a017kstatus IN ('A', 'TA') AND
a017kjantina IN ('L', 'P')
答案 1 :(得分:0)
由于您在每个查询中从同一个表中选择相同的字段,因此您只需要合并其where
- 子句。
作为第一步,它看起来像这样:
SELECT a017kstatus
FROM a017
WHERE a017kstatus='A' AND a017kjantina='L'
AND a017kstatus='A' AND a017kjantina='P'
AND a017kstatus='TA' AND a017kjantina='L'
AND a017kstatus='TA' AND a017kjantina='P'
但是可以使用in
- 运算符进一步简化:
SELECT a017kstatus
FROM a017
WHERE a017kstatus in ('A','TA')
AND a017kjantina in ('L','P')
答案 2 :(得分:0)
如果有一天你应该为a017kstatus
提取SELECT a017kstatus
FROM a017
WHERE (a017kstatus ='A'AND a017kjantina in ('L','P') )
OR (a017kstatus ='L'AND a017kjantina in ('L','P', 'xx') )
的不同值('xx'只是一个例子):
<?php echo $_SERVER['REMOTE_ADDR'];?>
答案 3 :(得分:-1)
联盟应该在这里帮助你:
SELECT a017kstatus FROM a017 WHERE a017kstatus='A' AND a017kjantina='L'
Union
SELECT a017kstatus FROM a017 WHERE a017kstatus='A' AND a017kjantina='P'
Union
SELECT a017kstatus FROM a017 WHERE a017kstatus='TA' AND a017kjantina='L'
Union
SELECT a017kstatus FROM a017 WHERE a017kstatus='TA' AND a017kjantina='P';