我有一些PHP代码可以生成多个MySql查询并组合结果。 我试图找到一种方法来组合查询,以便在两个查询中匹配的唯一字段被输出。
PHP代码输出示例。
SELECT LoadData_3 pow FROM tblLoadData WHERE LoadData_1 = 'test1' AND LoadData_2 = 'test2'
UNION ALL
SELECT LoadData_3 pow FROM tblLoadData WHERE LoadData_1 = 'test3' AND LoadData_2 = 'test4'
我只希望两个查询中的LoadData_3字段相同。
答案 0 :(得分:9)
使用INTERSECT
操作:
(SELECT LoadData_3 pow
FROM tblLoadData
WHERE LoadData_1 = 'test1'
AND LoadData_2 = 'test2')
INTERSECT -- return the intersection of the two queries
(SELECT LoadData_3 pow
FROM tblLoadData
WHERE LoadData_1 = 'test3'
AND LoadData_2 = 'test4')
修改强>
对于MySQL,您可以使用INNER JOIN USING (..)
SELECT pow -- Use DISTINCT pow instead if you want unique values (like INTERSECT)
FROM (SELECT LoadData_3 pow
FROM tblLoadData
WHERE LoadData_1 = 'test1'
AND LoadData_2 = 'test2') T1
INNER JOIN
(SELECT LoadData_3 pow
FROM tblLoadData
WHERE LoadData_1 = 'test3'
AND LoadData_2 = 'test4') T2
USING (pow)
或使用WHERE IN子句:
SELECT LoadData_3 pow -- Use DISTINCT pow instead if you want unique values (like INTERSECT)
FROM tblLoadData
WHERE LoadData_1 = 'test1'
AND LoadData_2 = 'test2'
AND LoadData_3 IN (SELECT LoadData_3 pow
FROM tblLoadData
WHERE LoadData_1 = 'test3'
AND LoadData_2 = 'test4')
答案 1 :(得分:2)